Android app log file on device

XDA Basics: How to take logs on Android

Logs are very useful when a developer is diagnosing an error with a piece of software. So, as a user, when you complain to a developer about a problem with their Android app or an aftermarket firmware (custom ROM), they’ll ask you to submit a log to help them troubleshoot the issue. Android includes a number of logs that deal with different parts of the firmware, and there are a number of ways to collect those logs. In this guide, we’ll talk about the various common logs and how you can collect them on Android for bug reports.

Before we start, you should set up Android Debug Bridge on your computer as you might need ADB access for some of these logs. We have a great guide on how to set up ADB on any computer.

Kernel panic logs

Kernel panic logs are useful to figure out what happened during an unsuccessful boot. If you’re trying to run a custom ROM but your phone is stuck at the boot loop, you can collect kernel panic logs to help the ROM developer find out what went wrong.

A majority of Android manufacturers use upstream ‘pstore’ and ‘ramoops’ drivers to store kernel logs after a panic. Ramoops writes its logs to the RAM before the system crashes. With root access, these logs can be retrieved from:

The file name could be slightly different but it’ll be in the pstore directory. You can get it using ADB pull or any other way you want. For example:

adb pull /sys/fs/pstore/console-ramoops C:\Users\Gaurav\Desktop\filename

Driver messages

The log from the driver messages buffer can be used to diagnose issues with system drivers and why something isn’t working. On Android, you can use the ‘dmesg’ output to get these logs. You’ll need root access to get these logs though. Use the following ADB command to export the complete log.

System logs

System logs are useful when something in the system throws an error. Android allows collecting system logs using Logcat. Log messages can be viewed in a Logcat window in Android Studio, or you can use the command line tool to pull them.

Several Android apps are also available in the Google Play store that allow easy access to these tools. We’ll talk about these apps later in this article. Moreover, several custom ROMs come with options in the Developers settings to collect the system logs.

To collect logs using ADB, use the following command. This command will export a continuous log, so use Ctrl + C to stop it.

You can use the -d parameter to export the complete log in one go.

If you want, you can also view or save the radio buffer using the following command.

If your device is rooted, you can use the Terminal app on the device itself to collect logs. To save a log using Terminal on your phone, type the following command so the log will be saved on your phone.

Android apps for collecting logs

Logcat Extreme

Logcat Extreme can help you read the logcat and dmesg outputs as well as record logs. It requires root access to show logs properly.

Читайте также:  Для чего делают прошивку андроид

Источник

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.

Источник

Android Debug Log

One very common trick developers use to debug their applications is to make calls to Console.WriteLine . However, on a mobile platform like Android there is no console. Android devices provides a log that you can use while writing apps. This is sometimes referred to as logcat due to the command that you type to retrieve it. Use the Debug Log tool to view the logged data.

Android Debug Log Overview

The Debug Log tool provides a way to view log output while debugging an app through Visual Studio. The debug log supports the following devices:

  • Physical Android phones, tablets, and wearables.
  • An Android Virtual device running on the Android Emulator.

The Debug Log tool does not work with Xamarin Live Player.

The Debug Log does not display log messages that are generated while the app is running standalone on the device (i.e., while it is disconnected from Visual Studio).

Accessing the Debug Log from Visual Studio

To open the Device Log tool, click Device Log (logcat) icon on the toolbar:

Alternately, launch the Device Log tool from one of the following menu selections:

  • View > Other Windows > Device Log
  • Tools > Android > Device Log

The following screenshot illustrates the various parts of the Debug Tool window:

Читайте также:  Джойстик для смартфона андроид bluetooth

Device Selector – Selects which physical device or running emulator to monitor.

Log Entries – A table of log messages from logcat.

Clear Log Entries – Clears all current log entries from the table.

Play/Pause – Toggles between updating or pausing the display of new log entries.

Stop – Halts the display of new log entries.

Search Box – Enter search strings in this box to filter for a subset of log entries.

When the Debug Log tool window is displayed, use the device pull-down menu to choose the Android device to monitor:

After the device is selected, the Device Log tool automatically adds log entries from a running app – these log entries are shown in the table of log entries. Switching between devices stops and starts device logging. Note that an Android project must be loaded before any devices will appear in the device selector. If the device does not appear in the device selector, verify that it is available in the Visual Studio device drop-down menu next to the Start button.

To open the Device Log, click View > Pads > Device Log:

The following screenshot illustrates the various parts of the Debug Tool window:

Device Selector – Selects which physical device or running emulator to monitor.

Log Entries – A table of log messages from logcat.

Clear Log Entries – Clears all current log entries from the table.

Search Box – Enter search strings in this box to filter for a subset of log entries.

Show Messages – Toggles the display of informational messages.

Show Warnings – Toggles the display of warning messages (warning messages are shown in yellow).

Show Errors – Toggles the display of error messages (warning messages are shown in red).

Reconnect – Reconnects to the device and refreshes the log entry display.

Add Marker – Inserts a marker message (such as — Marker N — ) after the latest log entry, where N is a counter that starts from 1 and increments by 1 as new markers are added.

When the Debug Log tool window is displayed, use the device pull-down menu to choose the Android device to monitor:

After the device is selected, the Device Log tool automatically adds log entries from a running app – these log entries are shown in the table of log entries. Switching between devices stops and starts device logging. Note that an Android project must be loaded before any devices will appear in the device selector. If the device does not appear in the device selector, verify that it is available in the Visual Studio device drop-down menu next to the Start button.

Accessing from the Command Line

Another option is to view the debug log via the command line. Open a command prompt window and navigate to the Android SDK platform-tools folder (typically, the SDK platform-tools folder is located at C:\Program Files (x86)\Android\android-sdk\platform-tools).

If only a single device (physical device or emulator) is attached, the log can be viewed by entering the following command:

Another option is to view the debug log via the command line. Open a Terminal window and navigate to the Android SDK platform-tools folder (typically, the SDK platform-tools folder is located at /Users/username/Library/Developer/Xamarin/android-sdk-macosx/platform-tools).

If only a single device (physical device or emulator) is attached, the log can be viewed by entering the following command:

If more than one device is attached, the device must be explicitly identified. For example adb -d logcat displays the log of the only physical device connected, while adb -e logcat shows the log of the only emulator running.

Читайте также:  Восстановить данные для андроида

More commands can be found by entering adb and reading the help messages.

Writing to the Debug Log

Messages can be written to the Debug Log by using the methods of the Android.Util.Log class. For example:

This produces output similar to the following:

It is also possible to use Console.WriteLine to write to the Debug Log – these messages appear in logcat with a slightly different output format (this technique is particularly useful when debugging Xamarin.Forms apps on Android):

This produces output similar to the following in logcat:

Interesting Messages

When reading the log (and especially when providing log snippets to others), perusing the log file in its entirety is often too cumbersome. To make it easier to navigate through log messages, start by looking for a log entry that resembles the following:

In particular, look for a line matching the regular expression that also contains the name of the application package:

This is the line which corresponds to the start of an activity, and most (but not all) of the following messages should relate to the application.

Notice that every message contains the process identifier (pid) of the process generating the message. In the above ActivityManager message, process 12944 generated the message. To determine which process is the process of the application being debugged, look for the mono.MonoRuntimeProvider message:

This message comes from the process that was started. All subsequent messages that contain this pid come from the same process.

Источник

Логирование в Android приложениях

Уверен, что всем разработчикам приложений на платформе Android знаком класс Log, позволяющий логировать различные события. По различным причинам, формат записи логов для каждого проекта может отличаться достаточно сильно — начиная от «AAA», «111111» и «I was here» до более-менее внятных — «Opening HTTP connection to habrahabr.ru». Под катом вы найдете пример функции, которая поможет навести порядок в логах.
Данный топик не претендует на оригинальность и универсальность. И поэтому, если в вашем проекте уже существует некий стандарт логирования событий, то смело проходите мимо — топик скорее ориентирован на начинающих разработчиков.

Как правило, ценность логов начинаешь понимать только когда заказчик матерясь отсылает лог на почту и просит засабмитить фикс через 5 минут. И если лог состоит из сообщений невнятного характера, то как минимум, разбр данного лога займет куда больше времени, чем хотелось бы.

Пытаемся навести порядок

Логи существуют для того, чтобы разработчик мог понять что, где и когда произошло. Найти ответ на вопрос «когда произошло» достаточно просто — в логах Андройд записывает время события. Нахождение ответа на вопрос «что произошло» так же не вызывает больших трудностей, если сообщение в лог было написано со смыслом, например: «Opening file. ». Вопрос «где произошло» оказывается наиболее сложным. Если проект большой, то придеться потратить время на нахождение нужного места кода, даже, если лог был написан со смыслом.

Если событие логируется с указанием Throwable (чаще Exception), например, метод public static int d (String tag, String msg, Throwable tr) , то в консоле сообщений будет выведен стек, который поможет быстро идентифицировать место логирования. Но использование данного метода без особой необходимости до безобразия перегрузит лог ненужной информацией.

Если же логируется просто текст, то при логировании можно явно указывать место вызова. Например:

Однако, писать такое каждый раз — дело утомительное и неблагодарное.

Ниже приведен пример класса Log , который делает это автоматически.

Использование класса очень простое:

Результатом логирования данным способом будут примерно следующие строки:

Примечание:
По понятным причинам, данный способ мало пригоден для приложений «пропущенных» через обфускатор.

В общем-то все.
Прошу прощения, если эта статья показалась слишком тривиальной для хабра.

Источник

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