- ADB Logcat Command – How to use ADB Logcat Command to capture debug logs from an Android device
- Basic requirements to use ADB Logcat
- Installation of ADB
- Adb Help Manual
- Using ADB Logcat
- Save Output of adb logcat to file (adb logcat save to file)
- adb logcat Filters
- Select Logcat for a specific device among multiple devices
- adb logcat Filter by App or Filtering by application package name
- Filtering Log Output
- XDA Basics: How to take logs on Android
- Kernel panic logs
- Driver messages
- System logs
- Android apps for collecting logs
- Logcat Extreme
- Adb logging in android
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:
- ADB binary or ADB driver installed in your computer or the machine in which you want to get the logs.
- An android phone or android emulator to run the APK file.
- 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:
- On the device, go to Settings > About Phone.
- Tap the Build number seven times to make Settings > Developer options available.
- 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,
- 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.
- 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
Источник
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.
Источник
Adb logging in android
Platform-tools: r31.0.3
ADB: 1.0.41 (31.0.3-7562133)
Fastboot: 31.0.3-7562133
Make_f2fs: 1.14.0 (2020-08-24)
Mke2fs: 1.46.2 (28-Feb-2021)
Последнее обновление утилит в шапке: 01.08.2021
ADB (Android Debug Bridge — Отладочный мост Android) — инструмент, который устанавливается вместе с Android-SDK и позволяет управлять устройством на базе ОС Android.
Работает на всех Android-устройствах, где данный функционал не был намеренно заблокирован производителем.
Здесь и далее: PC — ПК, компьютер к которому подключено устройство.
ADB — консольное приложение для PC, с помощью которого производится отладка Android устройств, в том числе и эмуляторов.
Работает по принципу клиент-сервер. При первом запуске ADB с любой командой создается сервер в виде системной службы (демона), которая будет прослушивать все команды, посылаемые на порт 5037.
Официальная страница
ADB позволяет:
- Посмотреть какие устройства подключены и могут работать с ADB.
- Просматривать логи.
- Копировать файлы с/на аппарат.
- Устанавливать/Удалять приложения.
- Удалять (очищать) раздел data.
- Прошивать (перезаписывать) раздел data.
- Осуществлять различные скрипты управления.
- Управлять некоторыми сетевыми параметрами.
Поставляется ADB в составе инструментария разработчика Андроид (Android SDK), который, в свою очередь входит в состав Android Studio.
Если что-то неправильно, то в списке подключенных устройств (List of devices attached) будет пусто.
Скрытые команды ADB
adb -d Команда посылается только на устройство подключенное через USB.
Внимание: Выдаст ошибку, если подключено больше одного устройства.
adb -e Команда посылается на устройство в эмуляторе.
Внимание: Выдаст ошибку, если подключено больше одного эмулятора.
adb -s Команда посылается на устройство с указанным серийным номером:
adb -p Команда посылается на устройство с указанным именем:
Если ключ -p не указан, используется значение переменной ANDROID_PRODUCT_OUT.
adb devices Список всех подсоединенных устройств.
adb connect [: ] Подсоединиться к андроид хосту по протококу TCP/IP через порт 5555 (по умолчанию, если не задан).
adb disconnect [ [: ]] Отсоединиться от андроид подключенного через TCP/IP порт 5555 (по умолчанию, если не задан).
Если не задан ни один параметр, отключиться от всех активных соединений.
adb push Копировать файл/папку PC->девайс.
adb pull [ ] Копировать файл/папку девайс->PC.
adb sync [ ] Копировать PC->девайс только новые файлы.
Ключи:
-l Не копировать, только создать список.
adb shell Запуск упрощенного unix shell.
Примеры использования
adb emu Послать команду в консоль эмулятора
adb install [-l] [-r] [-s] Послать приложение на устройство и установить его.
Пример: adb install c:/adb/app/autostarts.apk Установить файл autostarts.apk лежащий в папке /adb/app/ на диске с:
Ключи:
-l Блокировка приложения
-r Переустановить приложение, с сохранением данных
-s Установить приложение на карту памяти
Установка split apk
adb uninstall [-k] Удаление приложения с устройства.
Ключи:
-k Не удалять сохраненные данные приложения и пользователя.
adb wait-for-device Ждать подключения устройства.
adb start-server Запустить службу/демон.
adb kill-server Остановить службу/демон.
adb get-state Получить статус:
offline Выключен.
bootloader В режиме начальной загрузки.
device В режиме работы.
adb get-serialno Получить серийный номер.
adb status-window Непрерывный опрос состояния.
adb remount Перемонтировать для записи. Требуется для работы скриптов, которые изменяют данные на.
adb reboot bootloader Перезагрузка в режим bootloader.
adb reboot recovery Перезагрузка в режим recovery.
adb root Перезапуск демона с правами root
adb usb Перезапуск демона, прослушивающего USB.
adb tcpip Перезапуск демона, прослушивающего порт TCP.
adb ppp [параметры] Запуск службы через USB.
Note: you should not automatically start a PPP connection. refers to the tty for PPP stream. Eg. dev:/dev/omap_csmi_tty1
Параметры:
defaultroute debug dump local notty usepeerdns
FastBoot — консольное приложение для PC. Используется для действий над разделами
fastboot devices Список присоединенных устройств в режиме fastboot.
fastboot flash Прошивает файл .img в раздел устройства.
fastboot erase Стереть раздел.
Разделы: boot, recovery, system, userdata, radio
Пример: fastboot erase userdata Стирание пользовательских данных.
fastboot update Прошивка из файла имя_файла.zip
fastboot flashall Прошивка boot + recovery + system.
fastboot getvar Показать переменные bootloader.
Пример: fastboot getvar version-bootloader Получить версию bootloader.
fastboot boot [ ] Скачать и загрузить kernel.
fastboot flash:raw boot [ ] Создать bootimage и прошить его.
fastboot devices Показать список подключенных устройств.
fastboot continue Продолжить с автозагрузкой.
fastboot reboot Перезагрузить аппарат.
f astboot reboot-bootloader Перезагрузить девайсв режим bootloader.
Перед командами fastboot можно использовать ключи:
-w стереть данные пользователя и кэш
-s Указать серийный номер устройства.
-p
Указать название устройства.
-c Переопределить kernel commandline.
-i Указать вручную USB vendor id.
-b Указать в ручную базовый адрес kernel.
-n
Указать размер страниц nand. по умолчанию 2048.
Команду logcat можно использовать с машины разработки
$ adb logcat
или из удаленного shell
# logcat Каждое сообщение лога в Android имеет тэг и приоритет
Тэг – это строка указывающая компонент системы, от которого принято сообщение (например: View для системы view)
Приоритет – имеет одно из нижеследующих значений (в порядке от меньшего к большему):
V — Verbose (Низший приоритет).
D — Debug
I — Info
W — Warning
E — Error
F — Fatal
S — Silent (Наивысший приоритет, при котором ничего не выводится).
Получить список тэгов, используемых в системе, вместе с их приоритетами можно запустив logcat. В первых двух столбцах каждого из выведенных сообщений будут указаны / .
Пример выводимого logcat сообщения:
I/ActivityManager( 585): Starting activity: Intent
Для уменьшения вывода лога до приемлемого уровня нужно использовать выражения фильтра. Выражения фильтра позволяют указать системе нужные комбинации и , остальные сообщения система не выводит.
Выражения фильтра имеют следующий формат : . где указывает нужный тэг, указывает минимальный уровень приоритета для выбранного тэга. Сообщения с выбранным тэгом и приоритетом на уровне или выше указанного записываются в лог. Можно использовать любое количество пар : в одном выражении фильтра. Для разделения пар : используется пробел.
Пример ниже выводит в лог все сообщения с тэгом «ActivityManager» с приоритетом «Info» или выше, и сообщения с тэгом «MyApp» и приоритетом «Debug» или выше:
adb logcat ActivityManager:I MyApp:D *:S
Последний элемент в выражении фильтра *:S устанавливает приоритет «silent» для всех остальных тэгов, тем самым обеспечивая вывод сообщений только для «View» и «MyApp». Использование *:S – это отличный способ для вывода в лог только явно указанных фильтров (т.е. в выражении фильтра указывается «белый список» сообщений, а *:S отправляет все остальное в «черный список»).
При помощи следующего выражения фильтра отображаются все сообщения с приоритетом «warning» или выше для всех тэгов:
adb logcat *:W
Если logcat запускается на машине разработчика (не через удаленный adb shell), можно также установить значение выражения фильтра по умолчанию задав переменную окружения ANDROID_LOG_TAGS:
export ANDROID_LOG_TAGS=»ActivityManager:I MyApp:D *:S»
Следует обратить внимание что задав переменную окружения ANDROID_LOG_TAGS она не будет работать в эмуляторе/устройстве, если вы будете использовать logcat в удаленном shell или используя adb shell logcat.
Вышеописанная команда export работает в ОС *nix и не работает в Windows.
Контроль формата вывода лога
Сообщения лога в дополнение к тэгу и приоритету содержат несколько полей метаданных. Можно изменять формат вывода сообщений показывая только конкретные поля метаданных. Для этого используется параметр -v и указывается один из ниже перечисленных форматов вывода.
brief Показывать приоритет/тэг и PID процесса (формат по умолчанию).
process Показывать только PID.
tag Показывать только приоритет/тэг.
thread Показывать только процесс:поток и приоритет/тэг.
raw Показать необработанное сообщение, без полей метаданных.
time Показывать дату, время вызова, приоритет/тэг и PID процесса.
long Показывать все поля метаданных и отдельно сообщения с пустыми строками.
При запуске logcat можно указать формат вывода используя параметр -v:
adb logcat [-v
Источник