Android system data log

Логирование в 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 , который делает это автоматически.

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

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

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

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

Источник

Android system log file location

In Ubuntu, there is a /var/log/syslog file. What is the equavalent file of the ubuntus syslog in android? I have a rooted Android phone.

3 Answers 3

There are a few ways to view the System-Log — but finding the location of the log files is considerabaly harder. I will list 3 options that will allow you to view the logs (either on a device or computer), but I do not know where they are kept. I may be wrong, but from what I have gather, the Android System does not keep a «Log File». Rather, there is a buffer that contains the «Log» (again I may be wrong on this)!

Читайте также:  Нулс браво с лолой андроид

You first option is to install an app from the play-store called aLogCat . This app is very useful for both viewing and sending logs from your device. It can be setup to Email you the «Log Files» from your device. This method works best with root.

The second method works by using the Android SDK. Connect your device (with USB-Debugging enabled) and, at a Terminal enter the following:

The -d option tells adb to copy the entire File Log from the Android System. Because you seem to know how UNIX Systems work, I won’t explain the rest of the command.

A third option (if you are rooted, that is) is to install a Terminal Emulator on your Android device. Open the Terminal Emulator and enter the command:

Источник

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.

Читайте также:  Rome total war barbarian invasion android mod

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?

В системном журнале Android есть много интересных вещей, которые полезны во многих отношениях.

  • найти коренные причины проблем
  • определить ненадлежащие приложения

Как я могу просмотреть и изучить журнал Android?

Android 4.1 и новее

Предпочтительным способом является загрузка SDK и его использование adb logcat (требуется активировать «параметры разработчика» на устройстве).

Существуют приложения, доступные для просмотра полного системного журнала, однако они работают только на корневых устройствах или требуют ручного запуска команды, adb чтобы заставить их работать. Для получения дополнительной информации см. Этот вопрос.

Android 4.0 и старше

Вы можете либо загрузить SDK и использовать, adb logcat либо получить Logcat Extrem из Google Play Store, где журнал отображается прямо на вашем телефоне.

Расположение файла журнала

Существует несколько каталогов, в которых могут отображаться журналы (в том числе журналы о сбоях) — не все они стандартизированы (то есть некоторые могут быть привязаны к ПЗУ).

  • /data/anr : Некоторые файлы трассировки, похоже, попадают сюда (Dalvik записывает трассировки стека здесь в ANR, то есть «Приложение не отвечает» или «Force-Close»; см., Например, выдержки из журнала здесь )
  • /data/dontpanic кажется стандартным местоположением (AOSP) и содержит некоторые журналы сбоев, включая трассировки (см., например, viaForensics и StackOverflow )
  • /data/kernelpanics это другое место — у меня не было никакой «паники ядра» на моих устройствах Android, я пока не видел там никакого контента.
  • /data/panic/panic_daemon.config может указывать на другие места , сконфигурированных — на моем Droid 2 он упоминает /sdcard/panic_data/
  • упомянутый Droid 2 также имеет /data/panicreports каталог (здесь пусто)
  • /data/tombstones может содержать несколько tombstone_nn файлов ( nn будучи серийным, увеличивается с каждым новым файлом). Поскольку надгробные плиты размещаются для мертвых, это делается здесь для «процессов, погибших в результате аварии» (т.е. сбой) — и это то, что называется «дампами ядра» в системах Linux / Unix. Однако не все приложения создают надгробия; это должно быть явно разрешено разработчиком (см. Отладка дампов ядра Android ).

Может быть еще несколько мест, которые избежали меня; но поскольку большая часть записи ведется tmpfs , эти данные теряются при перезагрузке и не соответствуют вопросу OP.

Журнал команд для использования с терминальным приложением (или adb)

Несколько команд могут получить тонны информации. Для большинства из них рекомендуется перенаправить их в файл ( > filename.ext ) или передать через фильтр ( | grep search-for-this ):

Журнал ядра

Следующее работает без рута:

Читайте также:  От чего отключается андроид

Logcat

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

Получение информации об устройстве

И тонны этого: особенности устройства, информация об учетной записи, услуги .

Все в одном

Сделайте большой шар со всем вместе, от logcat до dumpstate:

Я уверен, что вы действительно хотите перенаправить эту последнюю команду . xD

Что-то о разрешениях

PS: Естественно, для доступа к этой информации может потребоваться root, так как большинство источников находятся во внутренней памяти.

Источник

How can I view and examine the Android log?

There is a lot of interesting stuff in the Android system log, that is helpful in many ways

  • find root causes of problems
  • identify misbehaving apps

How can I view and examine the Android log?

5 Answers 5

Android 4.1 and newer

The preferred way is to download the SDK and use adb logcat (requires to activate «developer options» on device).

There are apps available for viewing the full system log, however they only work on rooted devices or require issuing a manual command via adb to make them work. For more information view see this question.

Android 4.0 and older

You can either download the SDK and use adb logcat or get Logcat Extrem from the Google Play Store, which shows the log directly on your phone.

Log-File locations

There are several directories where logs (including those from crashes) might appear — not all of them are standardized (i.e. some may be ROM-specific).

  • /data/anr : Some trace files seem to get here (Dalvik writes stack traces here on ANR, i.e. «Application Not Responding» aka «Force-Close»; see e.g. log excerpts here)
  • /data/dontpanic seems to be a standard location (AOSP), and contains some crash logs including traces (see e.g. viaForensics and StackOverflow)
  • /data/kernelpanics is another location — not having had any «kernel panic» on my Android devices, I saw no content there yet.
  • the /data/panic/panic_daemon.config may point to other locations configured — on my Droid 2 it mentions /sdcard/panic_data/
  • mentioned Droid 2 also has a /data/panicreports directory (empty here)
  • /data/tombstones may hold several tombstone_nn files (with nn being a serial, increased with every new file). As tombstones are placed for the dead, it is done here for «processes died by accident» (i.e. crashed) — and it is what is referred to as «core dumps» on Linux/Unix systems. However, not all apps create tombstones; this must be explicitly enabled by the developer (see Debugging Android Core Dumps).

There may be some more locations which escaped me; but as most logging is done on tmpfs , these data are lost with a reboot, and would not match the OPs question.

Log commands to use with a terminal app (or adb)

Several commands can get you tons of information. For most of them, it is to recommend to re-direct them to a file ( > filename.ext ) or pipe them through a filter ( | grep search-for-this ):

Kernel log

The following works without root:

Logcat

Here you can e.g. specify what area you are interested in — radio, events.

Getting device info

And tons of it: Device specifics, account information, services.

All-in-One

Make a big ball with everything together, from logcat to dumpstate:

I’m pretty sure you really want to redirect that last command. xD

Источник

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