- 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
- Логирование в Android приложениях
- Пытаемся навести порядок
- 990x.top
- Простой компьютерный блог для души)
- Папка Logs на Андроиде — что это такое?
- Папка Logs на Андроиде — что это?
- Зачем нужны Log-файлы?
- Заключение
- Put your Android Studio on a diet
- How to make a deep clean of your Android Studio & Gradle junk files to fix up the mess.
- Clear your project directory
- Gradle cleaning
- Android Studio cleanup
- Extra cleaning
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.
Источник
Логирование в 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 , который делает это автоматически.
Использование класса очень простое:
Результатом логирования данным способом будут примерно следующие строки:
Примечание:
По понятным причинам, данный способ мало пригоден для приложений «пропущенных» через обфускатор.
В общем-то все.
Прошу прощения, если эта статья показалась слишком тривиальной для хабра.
Источник
990x.top
Простой компьютерный блог для души)
Папка Logs на Андроиде — что это такое?
Приветствую друзья. Данная заметка расскажет о папке Logs, которую можете заметить на смартфоне под управлением операционной системы Android.
Папка Logs на Андроиде — что это?
Содержит логи — специальные файлы, содержащие служебную информацию о работе некоторых системных функций/приложений телефона. Записываются ошибки, успешный результат, а также дополнительная информация.
Важно: данные файлы несут только информационный характер.
Стандартное расположение папки:
Без рут-доступа данная папка пользователю недоступна. Однако файлов внутри может становиться больше, свободное место телефона уменьшается.
В интернете найдена инструкция очистки логов системы:
- Наберите комбинацию *#9900#, на дисплее отобразится служебное меню.
- Нажмите пункт Delete dumpstate/logcat, кликните ОК.
- После данного действия логи телефона удалятся.
Способ был проверен на устройстве Самсунг Гелекси без рут-доступа. Действия проводить в стандартном диалере.
Данный способ на некоторых устройствах может не работать.
Зачем нужны Log-файлы?
Для обычных пользователей особой ценности не представляют. Внутри много системной информации, в которой нужно разбираться, чтобы извлечь пользу.
Обычно полезны программистам, которые анализируя логи находят ошибку в софте и исправляют.
Кроме OS Android, подобные файлы присутствуют в Windows, Linux и других операционках.
Заключение
- Папка Logs на Андроиде — содержит специальные файлы-отчеты, в которые записывается информация об ошибочных/успешных операциях некоторых программ/функций операционной системы Android.
- Данные файлы могут быть полезны при поиске проблем смартфона.
Источник
Put your Android Studio on a diet
How to make a deep clean of your Android Studio & Gradle junk files to fix up the mess.
Do you know that when you’re updating your Android Studio, Gradle or even dependencies, some old files are still present on your machine and can waste some disk free space?
On our laptops, disk space is limited and clearing those files will make you gain a lot of free space available. Having too many junk files may also slow down your machine and your builds!
In my case, I was also having strange build errors or gradle sync failures when it was working on my colleague’s machine.
It was time to do some deep cleaning and put our Android Studio on a diet by following some simple steps.
Clear your project directory
- Obviously, try to clean your project from android studio : “ Build -> Clean Project”. This will clear your build folders.
- Clear the cache of Android Studio using “ File -> Invalidate Caches / Restart” choose “ Invalidate and restart option” and close Android Studio.
- Remove your .gradle directory from the root of your project. It contains some Gradle cache files.
- Delete also the .idea directory ( make a backup before). It contains some project configuration files.
- Restart Android Studio.
Big project directories can weight around 500MB to 1GB.
Gradle cleaning
Now let’s take a look at Gradle files. If none of the above suggestions fix your problem, try these:
/.gradle directory. This is the Gradle home directory, containing caches, daemons and wrappers files. This is a really huge one, mine was
Inside those directories, you’ll have sub-directories for each version of Gradle you’ve been using. So, the more projects you have with different Gradle versions, the more sub-directories you will have.
You can delete those 3 directories:
- caches: Gradle cache files.
- daemon: essentially logs files of Gradle daemons.
- wrapper: different distributions of Gradle downloaded on you machine.
Android Studio cleanup
- Go to your Android home, usually
/.android and clear build-cache and cache directories. There are few MB to free here (
100MB for me)
In the
/Library/ directories, you will find the Android Studio preferences files, settings and plugins. You can clear the directories of previous version of Android Studio (> 1GB per version of AS). Starting with version 3.3, Android Studio will propose you to remove them after an update.
Android SDK cleaning
On Android Studio, check the SDK Manager and remove the following items:
- Old SDKs you don’t use anymore. I guess you’ll not miss the Android 3.0 SDK files.
- Remove the emulators you don’t use as they’re quite heavy ( some GB).
- I recommend to keep “Sources for Android xx” items as it will allow you to check the source code of the SDK from a previous version of Android & help you debugging.
- On the SDK Tools tab, click on “Show Packages Details” and uncheck the old build-tools or NDK versions.
- Delete unused emulators using the AVD.
You can gain easily 10GB with these steps.
Extra cleaning
There is some extra stuff you can clean too:
- Your download directory: you may have downloaded a lot of GIFs, video, Android Studio binaries that you can remove.
- Clear your local git branches that have been merged (don’t remove the ones that you still need!).
- Delete all those photoshopped pictures of your colleagues ( ͡° ͜ʖ ͡°).
- Clear your recycle bin.
That’s it ! You’ve gained some precious disk space on your machine and maybe fixed some weird issues with your Android Studio.
I don’t recommend to do a full clean everyday, you’ll waste time and your build time will be quite longer so you’ll be less productive. Take it only as a “spring cleaning” ritual.
I hope it helped you, and don’t forget to follow the Marie Kondo mantra and only keep things that spark joy.
Источник