- Логирование в Android приложениях
- Пытаемся навести порядок
- XDA Basics: How to take logs on Android
- Kernel panic logs
- Driver messages
- System logs
- Android apps for collecting logs
- Logcat Extreme
- Полный список
- Логи приложения
- Всплывающие сообщения
- Android Logging System
- Contents
- Overview
- Kernel driver
- System and Application logging
- Application log
- Event log
- System log
- ‘log’ command line tool
- Capturing stdout with logwrapper
- Logcat command
- Trick to couple Android logging to Linux kernel logging
Логирование в 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 , который делает это автоматически.
Использование класса очень простое:
Результатом логирования данным способом будут примерно следующие строки:
Примечание:
По понятным причинам, данный способ мало пригоден для приложений «пропущенных» через обфускатор.
В общем-то все.
Прошу прощения, если эта статья показалась слишком тривиальной для хабра.
Источник
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.
Источник
Полный список
В этом уроке мы:
— рассмотрим логи приложения и всплывающие сообщения
Project name: P0121_LogAndMess
Build Target: Android 2.3.3
Application name: LogAndMess
Package name: ru.startandroid.develop.logandmess
Create Activity: MainActivity
Создадим в main.xml экран, знакомый нам по прошлым урокам про обработчики:
Алгоритм приложения будет тот же. По нажатию кнопок меняется текст. Обработчик — Activity.
Сохраним, запустим. Убедимся, что все работает.
Логи приложения
Когда вы тестируете работу приложения, вы можете видеть логи работы. Они отображаются в окне LogCat. Чтобы отобразить окно откройте меню Window > Show View > Other … В появившемся окне выберите Android > LogCat
Должна появится вкладка LogCat
Рассмотрим эту вкладку подробней. Логи имеют разные уровни важности: ERROR, WARN, INFO, DEBUG, VERBOSE (по убыванию). Кнопки V D I W E (в кружках) – это фильтры и соответствуют типам логов. Опробуйте их и обратите внимание, что фильтр показывает логи не только своего уровня, но и уровней более высокой важности. Также вы можете создавать, редактировать и удалять свои фильтры – это мы рассмотрим чуть дальше.
Давайте смотреть, как самим писать логи. Делается это совсем несложно с помощью класса Log и его методов Log.v() Log.d() Log.i() Log.w() and Log.e(). Названия методов соответствуют уровню логов, которые они запишут.
Изменим код MainActivity.java. Возьмем все каменты из кода и добавим в DEBUG-логи с помощью метода Log.d. Метод требует на вход тэг и текст сообщения. Тэг – это что-то типа метки, чтобы легче было потом в куче системных логов найти именно наше сообщение. Добавим описание тега (TAG) и запишем все тексты каментов в лог.
Eclipse ругнется, что не знает класс Log. Обновите импорт (CTRL+SHIFT+O) и, если спросит, выберите android.util.Log. Запустим приложение, понажимаем кнопки и посмотрим логи
Видно, что все отлично записалось. Чтобы сделать просмотр удобней, создадим свой фильтр. Жмем значок +
Имя фильтра произвольное, например, «My logs». Log Tag – это как раз значение константы TAG, которая описана в нашем коде и использовалась в методе Log.d, т.е. — «myLogs«. Pid оставляем пустым, это id процесса. Уровень поставим Debug
и жмем OK. Появилась новая вкладка My logs, на которой отображаются логи, соответствующие только что созданному фильтру.
Мы помещали в лог текст, но разумеется, вы можете писать, например, значения интересующих вас переменных (приведенные к типу String).
Иногда бывает, что логи не отображаются во вкладке LogCat, хотя AVD запущен, приложение работает без проблем. В таком случае должно помочь следующее: в Eclipse идем в меню Window > Open Perspective > Other > DDMS. Откроется немного другой набор окон чем обычно. Там найдите вкладку Devices и в ней должно быть видно ваше AVD-устройство, кликните на него и логи должны появиться. Чтобы вернуться в разработку: Window > Open Perspective > Java.
Всплывающие сообщения
Приложение может показывать всплывающие сообщения с помощью класса Toast. Давайте подредактируем метод onClick. Сделаем так, чтобы всплывало сообщение о том, какая кнопка была нажата.
Разберем синтаксис вызова. Статический метод makeText создает View-элемент Toast. Параметры метода:
— context – пока не будем вдаваться в подробности, что это такое и используем текущую Activity, т.е. this.
— text – текст, который надо показать
— duration – продолжительность показа ( Toast.LENGTH_LONG — длинная, Toast.LENGTH_SHORT — короткая )
Toast создан и чтобы он отобразился на экране, вызывается метод show(). Сохраняем, запускаем, проверяем.
Если у вас есть Андроид-смартфон, я думаю вы уже видели подобные сообщения. Теперь вы знаете, как это делается )
На следующем уроке:
— создаем пункты меню
Присоединяйтесь к нам в Telegram:
— в канале StartAndroid публикуются ссылки на новые статьи с сайта startandroid.ru и интересные материалы с хабра, medium.com и т.п.
— в чатах решаем возникающие вопросы и проблемы по различным темам: Android, Kotlin, RxJava, Dagger, Тестирование
— ну и если просто хочется поговорить с коллегами по разработке, то есть чат Флудильня
— новый чат Performance для обсуждения проблем производительности и для ваших пожеланий по содержанию курса по этой теме
Источник
Android Logging System
This article describes the Android logging system
Contents
Overview
The Android system has a logging facility that allows system-wide logging of information, from applications and system components. This is separate from the Linux kernel’s own logging system, which is accessed using ‘dmesg’ or ‘/proc/kmsg’. However, the logging system does store messages in kernel buffers.
The logging system consists of:
- a kernel driver and kernel buffers for storing log messages
- C, C++ and Java classes for making log entries and for accessing the log messages
- a standalone program for viewing log messages (logcat)
- ability to view and filter the log messages from the host machine (via eclipse or ddms)
There are four different log buffers in the Linux kernel, which provide logging for different parts of the system. Access to the different buffers is via device nodes in the file system, in /dev/log.
The four log buffers are:
- main — the main application log
- events — for system event information
- radio — for radio and phone-related information
- system — a log for low-level system messages and debugging
Up until 2010, only the first three logs existed. The system log was created to keep system messages in a separate buffer (outside of ‘/dev/log/main’) so that a single verbose application couldn’t overrun system messages and cause them to be lost.
Each message in the log consists of a tag indicating the part of the system or application that the message came from, a timestamp, the message log level (or priority of the event represented by the message) and the log message itself.
All of the log buffers except for ‘event’ use free-form text messages. The ‘event’ buffer is a ‘binary’ buffer, where the event messages (and event parameters) are stored in binary form. This form is more compact, but requires extra processing when the event is read from the buffer, as well as a message lookup database, to decode the event strings.
The logging system automatically routes messages with specific tags into the radio buffer. Other messages are placed into their respective buffers when the the log class or library for that buffer is used.
Kernel driver
The kernel driver for logging is called the ‘logger’. See Android logger
System and Application logging
Application log
An Android application includes the android.util.Log class, and uses methods of this class to write messages of different priority into the log.
Java classes declare their tag statically as a string, which they pass to the log method. The log method used indicates the message «severity» (or log level). Messages can be filtered by tag or priority when the logs are processed by retrieval tools (logcat).
Event log
Event logs messages are created using android.util.EventLog class, which create binary-formatted log messages. Log entries consist of binary tag codes, followed by binary parameters. The message tag codes are stored on the system at: /system/etc/event-log-tags. Each message has the string for the log message, as well as codes indicating the values associated with (stored with) that entry.
System log
Many classes in the Android framework utilize the system log to keep their messages separate from (possibly noisy) application log messages. These programs use the android.util.Slog class, with its associated messages.
In all cases, eventually a formatted message is delivered through the C/C++ library down to the kernel driver, which stores the message in the appropriate buffer.
‘log’ command line tool
There is a ‘log’ command line tool that can be used to create log entries from any program. This is built into the ‘toolbox’ multi-function program.
The usage for this is:
Capturing stdout with logwrapper
It is sometimes useful to capture stdout from native applications into the log. There is a utility called ‘logwrapper’ which can be used to run a program, and redirect it’s stdout into log messages.
The logwrapper usage is:
Source for logwrapper is at: system/core/logwrapper/logwrapper.c
Logcat command
You can use the ‘logcat’ command to read the log. This command is located in /system/bin in the local filesystem, or you can access the functionality using the ‘adb logcat’ command.
Some quick notes:
- Log messages each have a tag and priority.
- You can filter the messages by tag and log level, with a different level per tag.
- You can specify (using a system property) that various programs emit their stdout or stderr to the log.
Trick to couple Android logging to Linux kernel logging
Note that the android logging system is completely separate from the Linux kernel log system (which uses printk inside the kernel to save messages and dmesg to extract them). You can write to the kernel log from user space by writing to /dev/kmsg.
I’ve seen a reference to couple the two together, to redirect android messages into the kernel log buffer, using the ‘logcat’ program launched from init, like below:
I’m not sure why you’d want to do this (maybe to put all messages into a single stream? With the same timestamp, if kernel message timestamping is on?)
Источник