Android write to logcat

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. Можно проверить следующим образом:

Читайте также:  Android смартфоны с диагональю до 5 дюймов

Способ для продвинутых — например, требуется релиз с выводом в лог, или наоборот — debug с выключенным выводом. В этом случае можно создать собственный параметр и добавить его в секцию buildType gradle-файла:

В этом случае конфигурация releaseWithLog будет являться релизной сборкой с ведением логов. Естественно, в коде слегка поменяется проверка:

LogCat на устройстве

Попался в сети пример для просмотра сообщений LogCat на устройстве. С примером не разбирался, оставлю здесь на память.

Источник

Android LogCat And Logging Best Practice

android.util.Log is the log class that provides the log function. It provides the below methods to log data into the LogCat console.

1. Android Log Methods.

  1. Log.v(): Print verbose level log data. The verbose level is the lowest log level, if you print so much this kind of log data, it is not meaningful.
  2. Log.d(): Print debug level log data. Debug level is one step higher than verbose level. Debug log data is usually useful in android application development and testing.
  3. Log.i(): Print info level log data. Info level is one step higher than debug level. Info log data is used to collect user actions and behaviors.
  4. Log.w(): Print warn level log data. Warn level is one step higher than info level. When you see this kind of log data, it means your code exists potential risks, you need to check your code carefully.
  5. Log.e(): Print error level log data. Error level is the highest level. It is always used in java code catch block to log exception or error information. This kind of log data can help you to find out the root cause of app crashes.

2. Android Log Methods Example.

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/ciBUMesUfVo

  1. This example is very simple. When you click the button, it will print above 5 kinds of log data in the LogCat console.
  2. When you input the search keyword LogActivity in the LogCat panel, the app log data will be filtered out. For each line of log data, there are the log time, class name, and log message.
  3. You can also filter out the log data by it’s type, verbose, info, debug, warn, or error. This can make log data search more easily and accurately, you can see the below demo video.

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/zyUvmTF_Mzw

  1. Click the Settings icon in the LogCat panel, you can configure which column to be displayed for each line of the log.
  2. The columns include Show date and time, Show process and thread IDs(PID-TID), Show package name, Show tag, you can see it in the below picture.

Источник

Reading and Writing Logs

In this document

The Android logging system provides a mechanism for collecting and viewing system debug output. Logcat dumps a log of system messages, which include things such as stack traces when the emulator throws an error and messages that you have written from your application by using the Log class. You can run LogCat through ADB or from DDMS, which allows you to read the messages in real time.

Читайте также:  Примеры оформления рабочего стола андроид

The Log class

Log is a logging class that you can utilize in your code to print out messages to the LogCat. Common logging methods include:

The LogCat will then output something like:

Using LogCat

You can use LogCat from within DDMS or call it on an ADB shell. For more information on how to use LogCat within DDMS, see Using DDMS. To run LogCat, through the ADB shell, the general usage is:

You can use the logcat command from your development computer or from a remote adb shell in an emulator/device instance. To view log output in your development computer, you use

and from a remote adb shell you use

The following table describes the logcat command line options:

-c Clears (flushes) the entire log and exits.
-d Dumps the log to the screen and exits.
-f Writes log message output to . The default is stdout .
-g Prints the size of the specified log buffer and exits.
-n Sets the maximum number of rotated logs to . The default value is 4. Requires the -r option.
-r Rotates the log file every of output. The default value is 16. Requires the -f option.
-s Sets the default filter spec to silent.
-v Sets the output format for log messages. The default is brief format. For a list of supported formats, see Controlling Log Output Format.

Filtering Log Output

Every Android log message has a tag and a priority associated with it.

  • The tag of a log message is a short string indicating the system component from which the message originates (for example, «View» for the view system).
  • The priority is one of the following character values, ordered from lowest to highest priority:
    • V — Verbose (lowest priority)
    • D — Debug
    • I — Info
    • W — Warning
    • E — Error
    • F — Fatal
    • S — Silent (highest priority, on which nothing is ever printed)

You can obtain a list of tags used in the system, together with priorities, by running LogCat and observing the first two columns of each message, given as

Here’s an example of logcat output that shows that the message relates to priority level «I» and tag «ActivityManager»:

To reduce the log output to a manageable level, you can restrict log output using filter expressions. Filter expressions let you indicate to the system the tags-priority combinations that you are interested in — the system suppresses other messages for the specified tags.

A filter expression follows this format tag:priority . , where tag indicates the tag of interest and priority indicates the minimum level of priority to report for that tag. Messages for that tag at or above the specified priority are written to the log. You can supply any number of tag:priority specifications in a single filter expression. The series of specifications is whitespace-delimited.

Here’s an example of a filter expression that suppresses all log messages except those with the tag «ActivityManager», at priority «Info» or above, and all log messages with tag «MyApp», with priority «Debug» or above:

The final element in the above expression, *:S , sets the priority level for all tags to «silent», thus ensuring only log messages with «View» and «MyApp» are displayed. Using *:S is an excellent way to ensure that log output is restricted to the filters that you have explicitly specified — it lets your filters serve as a «whitelist» for log output.

Читайте также:  Взлом телефонов через андроид

The following filter expression displays all log messages with priority level «warning» and higher, on all tags:

If you’re running LogCat from your development computer (versus running it on a remote adb shell), you can also set a default filter expression by exporting a value for the environment variable ANDROID_LOG_TAGS :

Note that ANDROID_LOG_TAGS filter is not exported to the emulator/device instance, if you are running LogCat from a remote shell or using adb shell logcat .

Controlling Log Output Format

Log messages contain a number of metadata fields, in addition to the tag and priority. You can modify the output format for messages so that they display a specific metadata field. To do so, you use the -v option and specify one of the supported output formats listed below.

  • brief — Display priority/tag and PID of the process issuing the message (the default format).
  • process — Display PID only.
  • tag — Display the priority/tag only.
  • raw — Display the raw log message, with no other metadata fields.
  • time — Display the date, invocation time, priority/tag, and PID of the process issuing the message.
  • threadtime — Display the date, invocation time, priority, tag, and the PID and TID of the thread issuing the message.
  • long — Display all metadata fields and separate messages with blank lines.

When starting LogCat, you can specify the output format you want by using the -v option:

Here’s an example that shows how to generate messages in thread output format:

Note that you can only specify one output format with the -v option.

Viewing Alternative Log Buffers

The Android logging system keeps multiple circular buffers for log messages, and not all of the log messages are sent to the default circular buffer. To see additional log messages, you can run the logcat command with the -b option, to request viewing of an alternate circular buffer. You can view any of these alternate buffers:

  • radio — View the buffer that contains radio/telephony related messages.
  • events — View the buffer containing events-related messages.
  • main — View the main log buffer (default)

The usage of the -b option is:

Here’s an example of how to view a log buffer containing radio and telephony messages:

Viewing stdout and stderr

By default, the Android system sends stdout and stderr ( System.out and System.err ) output to /dev/null . In processes that run the Dalvik VM, you can have the system write a copy of the output to the log file. In this case, the system writes the messages to the log using the log tags stdout and stderr , both with priority I .

To route the output in this way, you stop a running emulator/device instance and then use the shell command setprop to enable the redirection of output. Here’s how you do it:

The system retains this setting until you terminate the emulator/device instance. To use the setting as a default on the emulator/device instance, you can add an entry to /data/local.prop on the device.

Debugging Web Apps

If you’re developing a web application for Android, you can debug your JavaScript using the console JavaScript APIs, which output messages to LogCat. For more information, see Debugging Web Apps.

Источник

Оцените статью