Android logcat to file

ADB Logcat Command – How to use ADB Logcat Command to capture debug logs from an Android device

ADB Logcat is the command-line tool for dump logs or print logs of the android system to the screen. Logcat can print sys logs, stack traces, thrown error messages from the device, and the Log class messaged written in the app.

In this article, you will learn what is ADB Logcat and how to use adb logcat command practically for your android testing or debugging tasks with proper examples. how to filter the targeted logs, how to save adb logcat output to file, and many more things.

While doing android app security testing, adb logcat performs a very helpful job. This tool will help us better understand the android application at run time.

Android Debug Bridge (ADB) Logcat bash command provides many features like we can filter the logs for specific packages, specific activities within the apps, filter the logs based on the buffer, filter the logs based on log priorities, filter the logs by tag names, etc.

Basic requirements to use ADB Logcat

Ive listed some basic requirements to use adb logcat command:

  1. ADB binary or ADB driver installed in your computer or the machine in which you want to get the logs.
  2. An android phone or android emulator to run the APK file.
  3. Android device or emulator has USB Debugging enabled in settings.

Installation of ADB

Installing ADB is very simple. For Ubuntu/Debian and its derivatives, use the following command:

Now, connect your android device with your PC using USB cable.

But, ADB only interacts with the android device once the “USB Debugging” option is enabled on the android device. USB Debugging option remains under Settings > Developer options.

Developer options is hidden by default, use the following steps to enable it:

  1. On the device, go to Settings > About Phone.
  2. Tap the Build number seven times to make Settings > Developer options available.
  3. Then enable the USB Debugging option.

Now use adb devices command to view the attached devices,

If you don’t have attached devices then connect the device using adb connect command. And if you are getting a “the ADB server version doesn’t match this client” Error then you can troubleshoot by the steps described here.

Adb Help Manual

We can access logcat manual by bash adb logcat —help command.

Using ADB Logcat

After proper installation of adb and proper connection connection with android device, we can use adb logcat command to start the android system log dumping.

This simple adb logcat command will show all adb logs.

Save Output of adb logcat to file (adb logcat save to file)

To save the output of adb logcat to file, we have multiple methods,

  1. adb logcat save to file using redirection operator of Linux bash command line.

After firing the following command start working on your android activities, the output will be stored under the specified file. Enter “Ctrl+C” to stop writing to file.

Disadvantage of this method is, you can’t watch what happending at run time. You have to open the file independenlty or first stop the output and observe the file.

To overcome this issue I have a different linux command to do both save and observe the ouptut parallely.

  1. Linux “tee” command for output of adb logcat save to file:
Читайте также:  Донт старв андроид без кеша

Using tee command with Pipe operator(|), we can observe the logcat output at run time and it will also be saved in the file parallelly. So it is a preferable method.

Note: To stop the saving output in file and monitoring it, press Ctrl+C

adb logcat Filters

Select Logcat for a specific device among multiple devices

If you have multiple devices connected with you PC, we have to choose with its device id.

To select the device when using adb logcat, use the following command with -s (adb Serial number) option.

adb logcat Filter by App or Filtering by application package name

To view the logs for specific apps, first of all we need to package name for the specific app. To get the package name we can use following command of ADB.

Identify the package name and we are ready to go.

I am using this customized command to get the logs for the specific apps

Filtering Log Output

Logcat logs got so called levels:

V — Verbose, D — Debug, I — Info, W — Warning, E — Error, F — Fatal, S — Silent

Those levels are specified when application uses those Log function:

if your code Log call is:

in logcat you’ll see this output:

So, this is the log convention:

For instance, if you want to show all the logs that have Fatal (F) level:

* is a what called a wild card – stands for all package names

Источник

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»:

Читайте также:  Андроид ошибка com android phone

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.

Источник

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 на устройстве. С примером не разбирался, оставлю здесь на память.

Источник

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