- Logcat
- Быстрое отключение журналирования
- LogCat на устройстве
- Запись и просмотр логов при помощи Logcat
- Android Studio Logcat and Recycler View
- Android Studio Logcat and Recycler View
- Android Studio Logcat
- How to start the logcat window?
- Logcat window
- Logcat levels
- Making your own level
- Options to fill over there
- Android Studio Recycler View
- How to use Recycler View?
- For Java
- For Kotlin
- Conclusion
Logcat
В Android SDK входит набор инструментов, предназначенных для отладки. Самый важный инструмент при отладке — это LogCat (очень красивое название, которое можно перевести как Логичный Кот). Он отображает сообщения логов (журнал логов), рассылаемые при помощи различных методов.
Рассмотрим на примере. Очень часто программисту нужно вывести куда-то промежуточные результаты, чтобы понять, почему программа не работает. Особо хитрые временно размещают на экране текстовую метку и выводят туда сообщение при помощи метода textView.setText(«Здесь был Васька»). Но есть способ лучше. В Android есть специальный класс android.util.Log для подобных случаев.
Класс android.util.Log позволяет разбивать сообщения по категориям в зависимости от важности. Для разбивки по категориям используются специальные методы, которые легко запомнить по первым буквам, указывающие на категорию:
- Log.e() — ошибки (error)
- Log.w() — предупреждения (warning)
- Log.i() — информация (info)
- Log.d() — отладка (degub)
- Log.v() — подробности (verbose)
- Log.wtf() — очень серьёзная ошибка! (What a Terrible Failure!, работает начиная с Android 2.2)
- Log.meow() — когда жрать дадут? (MEOW!) Недокументированный метод, используйте на свой страх и риск. Работает не на всех устройствах
В первом параметре метода используется строка, называемая тегом. Обычно принято объявлять глобальную статическую строковую переменную TAG в начале кода:
Некоторые в сложных проектах используют следующий вариант, чтобы понимать, в каком классе происходит вызов:
Далее уже в любом месте вашей программы вы вызываете нужный метод журналирования с этим тегом:
Также используется в исключениях:
Пользователи не видят этот журнал. Но, вы, как разработчик, можете увидеть его через программу LogCat, доступный в Android Studio.
Полный вид сообщения выглядит следующим образом.
03-09 20:44:14.460 3851-3879 / ru.alexanderklimov.cat I/OpenGLRenderer : Initialized EGL, version 1.4
- 03-09 20:44:14.460 Date/Time
- 3851-3879 Process & Thread IDs
- ru.alexanderklimov.cat Package name
- I/OpenGLRenderer Tag
- Initialized EGL, version 1.4 Message
Подобные длинные сообщения не всегда удобны для чтения. Вы можете убрать ненужные элементы. Для этого выберите значок LogCat Header в виде шестерёнки и уберите флажки у опций.
В LogCat вы можете отфильтровать сообщение по заданному типу, чтобы видеть на экране только свои сообщения. Для этого выберите нужный тип тега из выпадающего списка Verbose.
Типы сообщений можно раскрасить разными цветами через настройки File | Settings | Editor | Colors Scheme | Android Logcat.
Для отслеживания сообщений с заданным текстом введите в поле поиска нужную строку и нажмите Enter.
Также активно используйте варианты из других выпадающих списков. Например, выбирайте свой пакет из второй колонки, а в последней выбирайте Show only selected application. Для более точной настройки используйте Edit Fiter Configuration.
По умолчанию, окно LogCat выводится в нижней части студии. При желании, можно выбрать другие варианты через значок настроек окна.
LogCat также можно запустить из командной строки:
Параметры командной строки смотрите в документации.
Быстрое отключение журналирования
Настоятельно рекомендуется удалять все вызовы LogCat в готовых приложениях. Если проект очень большой и вызовы журналирования разбросаны по всем местам кода, то ручное удаление (или комментирование) становится утомительным занятием. Многие разработчики используют следующую хитрость — создают обёртку вокруг вызова методов LogCat.
Теперь остаётся только присвоить нужное значение переменной isDebug перед созданием готового apk-файла для распространения.
Способ устарел. В 17-й версии Android Build Tools появился класс BuildConfig, содержащий статическое поле DEBUG. Можно проверить следующим образом:
Способ для продвинутых — например, требуется релиз с выводом в лог, или наоборот — debug с выключенным выводом. В этом случае можно создать собственный параметр и добавить его в секцию buildType gradle-файла:
В этом случае конфигурация releaseWithLog будет являться релизной сборкой с ведением логов. Естественно, в коде слегка поменяется проверка:
LogCat на устройстве
Попался в сети пример для просмотра сообщений LogCat на устройстве. С примером не разбирался, оставлю здесь на память.
Источник
Запись и просмотр логов при помощи Logcat
Окно Logcat в Android Studio отображает логи в режиме реального времени и сохраняет историю, чтобы можно было просматривать старые сообщения. Стоит отметить, что по умолчанию LogCat показывает журнал, связанный с последним запущенным приложением.
Для открытия окна LogCat необходимо открыть меню Window -> Show View -> Other и во вкладке android выбрать LogCat.
Логи разделены по степени важности на пять групп (по убыванию):
- ERROR– ошибки
- WARN– предупреждения
- INFO– информация
- DEBUG– отладка
- VERBOSE– подробности
Фильтр по группам в LogCat показывает логи не только своего уровня, но и уровней более важные.
Для того чтобы написать в лог свое сообщение в есть специальный класс – android.util.Log. В котором определены методы для записи сообщений, названные по первым буквам соответствующих категорию: Log.e(), Log.w(), Log.i(), Log.d(), Log.v().
В дополнение определен метод Log.wtf(), используемый при очень серьёзной ошибке (What a Terrible Failure!). Такое сообщение соответствует состоянию, которое не может быть получено при штатной работе приложения. Сообщение относится к категории ASSERT.
Методы получают на вход тэг и текст сообщения. Тэг необходим для упрощения поиска своих сообщений в огромном потоке системных логов. Обычно в качестве гэга используют объявленную в начале кода глобальную статическую строковую переменную TAG.
private static final String TAG = «MyTAG»;
Однако в сложных проектах целесообразно понимать, в каком классе произошел вызов.
private static final String TAG = this.getClass().getSimpleName();
Пример использования метода журналирования:
Log.d(TAG, «Кто здесь?!»);
Пример при обработке исключения:
З.Ы. Журнал сообщений не виден пользователям. Для доступа к нему можно воспользоваться LogCat, который доступен в идущих вместе с Android-SDK ADB (Android Debug Bridge — Отладочный мост Android) и DDMS (Dalvik Debug Monitor Server).
Источник
Android Studio Logcat and Recycler View
Android Studio Logcat and Recycler View
Android Studio Logcat and Recycler View. Do you want to work on the android studio logcat and the recycler view? This article will deal with all about that. This is your one-stop to get all the knowledge about the android logcat. Keep reading.
Android Studio Logcat
We will start this article with the Android studio logcat. The first question is, “what is an android studio logcat?”
Logcat is one of the most needed part of android app development. It shows all the logs log. But what kind of log. It shows the logs related to all the crashes the app goes through, any error in the code, etc. The logs come from the emulator or your device on which you are using the app.
Mainly three kinds of messages popup in logcat:
- System.out.println
- exceptions
- android.util.Log
android.util.Log is used to properly log the errors on the application. All the log has some level. These levels tell how severe the Error is. Using the android.util.log you can filter all the errors based on the levels. Some of the example of the log level:
How to start the logcat window?
There are several ways to open the log cat window. We will see some of them.
The first way is by just pressing Alt+F6 on the keyboard when you press the combination of these two keys; the logcat window automatically opens.
The second way is by using the menu bar. First of all, click the view button, then click on the tools window, then click on the logcat option. This method will also open the logcat window. Android Studio Logcat
The third way is by using the bottom panel of the android studio. To use this method, just click on the Logcat tool button. Android Studio Logcat and Recycler View.
Logcat window
The logcat window has mainly five types of options. We will see them one by one.
The first is the device selection menu. This menu allows you to select the device from the list of your devices on which you want to work on or from which you want to get the logs.
The second is the app selection menu. This menu gives you the option to select between the multiple apps you are working on.
The third is the filter menu. This menu allows you to filter your logs on the basis of the level. It means that the log which has more severity will show on the top.
The fourth is the search. It helps you in searching for the log using some specific search keyword. This thing comes handy when you know what log you want to see.
The fifth is the “show only selected application.” If this option is activated, then you can only see the logs coming from that particular app. If you don’t select this option, it will show all the logs coming from that device.
Logcat levels
There is mainly 6 kind of filter in android studio. A developer can make their own level. We will talk about creating our own level later.
- The first level is Verbose. The verbose is the least severe level of all. It shows all the logs from the app without filtering the logs on any severity.
- The second is the Debug. This is the one next level of severity. It shows only the logs relegated to the debug of the application. This gives the user an option to check only the information related to debugging.
- The third is Info. This shows all the informational logs related app. Information like the sensors are working or not; the app is connected to the internet or not and much other information.
- The fourth is the Warn. The warn shows all the warnings in the app. Warnings are related to those statements which may cause errors in the future.
- The fifth one is Error. The Error shows all the errors related to the application. This shows the possible problem in the application.
- The last one is the Assert. The Assert shows the logs of the issues which should never happen in the first place. This is the highest severity in the android studio. These are those issues that will cause a big problem for the application.
Making your own level
As we talked earlier that we can create our personal level in the logcat. Here we are going to know about that. Each and every log in android studio uses a tag. By using those tags, we can create our own level. This thing comes handy when you want to trace back the log by your own filter. To create your own level, follow these steps. Android Studio Logcat and Recycler View.
Step 1. Click on the show selected application option. A menu will appear.
Step 2. Select the “edit filter configuration” option. It will take you to a new window, where you will be able to create a new filter.
Step 3. Enter all the variables correctly and hit ok. It will generate a new level/filter for the developer.
Options to fill over there
- Filter Name: This field will take the input of the name of the filter you want. Make sure to keep it unique.
- Log tag: This is the most needed option. This will help you to identify which type of message you want to filter using this new filter. Choose your tag correctly.
- Log message. This option tells you the message you want to see in the log. Create your message which defines the circumstances clearly, so that the other user can understand it also.
- Package name: This is an optional function. This is used if you want to get logs from a certain app if you want, so then enter the name of the package of the application.
- PID: PID stands for process id. This will help you to log a specific process. If you want to log from a specific process, then enter the process id else leave it blank.
As of now, we know everything about the Logcat. Now we will see how to clean the logcat window. Cleaning the logcat window is very simple. You just have to click the trash button on the side of the logcat window, and your logcat window will be clean.
Android Studio Recycler View
Android Studio Recycler view is an option to create a list in the android application. It is much better than the list view. It is a moreover dynamic kind of list which keeps changes from time to time. The list we have seen the food ordering apps are made from recycler view. As the food menu keep changing, we use this method.
There is a lot of optimization in the recycler view than the list view. Android Studio Recycler View
How to use Recycler View?
To use the recycler view, we need to add the recycler view library, which is V7 support libraries. To import the follow the steps.
Step 1. Open your application and head to build.gradle file.
Step 2. Insert the following code in the dependencies section.
Now once you have inserted this code, you have to connect the recycler view to the layout manager, and you also have to add the adapter to display the data. Insert this code to do so.
Read my other post: Infinity Blade on Android
For Java
For Kotlin
Now you can insert your code to do your project. That’s all for recycler view
Conclusion
Android Studio Logcat and Recycler View. We have seen how to access the logcat and how to work with the recycler view in the android studio. Try on your projects. I hope you like the post.
Источник