- Logcat
- Быстрое отключение журналирования
- LogCat на устройстве
- Логирование в Android приложениях
- Пытаемся навести порядок
- Android Essentials: Application Logging
- Step 1: Create an Android Application
- Step 2: Logging Options for Android Applications
- Step 3: Adding Log Support to an Activity Class
- Step 4: Monitoring Application Log Output – The Easy Way
- Step 5:Monitoring Application Log Output – Creating Log Filters
- Performance Considerations with Logging
- Conclusion
- Debugging and Logging Android App
- Introduction
- Requirements
- Major problem in android app development
- Following most debugging tools and libraries for logging android app
- 1. Bugfender
- 2. Fabric Crashlytics (Firebase)
- 3. Stetho
- 4. Timber’s Requirement:
- 5. Android Debug Database
Logcat
В Android SDK входит набор инструментов, предназначенных для отладки. Самый важный инструмент при отладке — это LogCat (очень красивое название, которое можно перевести как Логичный Кот). Он отображает сообщения логов (журнал логов), рассылаемые при помощи различных методов.
Рассмотрим на примере. Очень часто программисту нужно вывести куда-то промежуточные результаты, чтобы понять, почему программа не работает. Особо хитрые временно размещают на экране текстовую метку и выводят туда сообщение при помощи метода textView.setText(«Здесь был Васька»). Но есть способ лучше. В Android есть специальный класс android.util.Log для подобных случаев.
Класс android.util.Log позволяет разбивать сообщения по категориям в зависимости от важности. Для разбивки по категориям используются специальные методы, которые легко запомнить по первым буквам, указывающие на категорию:
- Log.e() — ошибки (error)
- Log.w() — предупреждения (warning)
- Log.i() — информация (info)
- Log.d() — отладка (degub)
- Log.v() — подробности (verbose)
- Log.wtf() — очень серьёзная ошибка! (What a Terrible Failure!, работает начиная с Android 2.2)
- Log.meow() — когда жрать дадут? (MEOW!) Недокументированный метод, используйте на свой страх и риск. Работает не на всех устройствах
В первом параметре метода используется строка, называемая тегом. Обычно принято объявлять глобальную статическую строковую переменную TAG в начале кода:
Некоторые в сложных проектах используют следующий вариант, чтобы понимать, в каком классе происходит вызов:
Далее уже в любом месте вашей программы вы вызываете нужный метод журналирования с этим тегом:
Также используется в исключениях:
Пользователи не видят этот журнал. Но, вы, как разработчик, можете увидеть его через программу LogCat, доступный в Android Studio.
Полный вид сообщения выглядит следующим образом.
03-09 20:44:14.460 3851-3879 / ru.alexanderklimov.cat I/OpenGLRenderer : Initialized EGL, version 1.4
- 03-09 20:44:14.460 Date/Time
- 3851-3879 Process & Thread IDs
- ru.alexanderklimov.cat Package name
- I/OpenGLRenderer Tag
- Initialized EGL, version 1.4 Message
Подобные длинные сообщения не всегда удобны для чтения. Вы можете убрать ненужные элементы. Для этого выберите значок LogCat Header в виде шестерёнки и уберите флажки у опций.
В LogCat вы можете отфильтровать сообщение по заданному типу, чтобы видеть на экране только свои сообщения. Для этого выберите нужный тип тега из выпадающего списка Verbose.
Типы сообщений можно раскрасить разными цветами через настройки File | Settings | Editor | Colors Scheme | Android Logcat.
Для отслеживания сообщений с заданным текстом введите в поле поиска нужную строку и нажмите Enter.
Также активно используйте варианты из других выпадающих списков. Например, выбирайте свой пакет из второй колонки, а в последней выбирайте Show only selected application. Для более точной настройки используйте Edit Fiter Configuration.
По умолчанию, окно LogCat выводится в нижней части студии. При желании, можно выбрать другие варианты через значок настроек окна.
LogCat также можно запустить из командной строки:
Параметры командной строки смотрите в документации.
Быстрое отключение журналирования
Настоятельно рекомендуется удалять все вызовы LogCat в готовых приложениях. Если проект очень большой и вызовы журналирования разбросаны по всем местам кода, то ручное удаление (или комментирование) становится утомительным занятием. Многие разработчики используют следующую хитрость — создают обёртку вокруг вызова методов LogCat.
Теперь остаётся только присвоить нужное значение переменной isDebug перед созданием готового apk-файла для распространения.
Способ устарел. В 17-й версии Android Build Tools появился класс BuildConfig, содержащий статическое поле DEBUG. Можно проверить следующим образом:
Способ для продвинутых — например, требуется релиз с выводом в лог, или наоборот — debug с выключенным выводом. В этом случае можно создать собственный параметр и добавить его в секцию buildType gradle-файла:
В этом случае конфигурация releaseWithLog будет являться релизной сборкой с ведением логов. Естественно, в коде слегка поменяется проверка:
LogCat на устройстве
Попался в сети пример для просмотра сообщений LogCat на устройстве. С примером не разбирался, оставлю здесь на память.
Источник
Логирование в 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 Essentials: Application Logging
In this quick tip tutorial, you’ll learn how to use application logging support in your Android applications for diagnostic purposes.
This quick tip shows you the steps to incorporate logging support into your applications and then use the LogCat logging utility to monitor your application’s log output, either on the emulator or a device that is attached to Eclipse via the debugger. This skill is invaluable for debugging issues, even when great debuggers are available for stepping through code.
Step 1: Create an Android Application
Begin by creating an Android project. Implement your Android application as normal. Once you’ve setup your Android project, you are ready to proceed with this quick tip.
Step 2: Logging Options for Android Applications
The Android SDK includes a useful logging utility class called android.util.Log. Logging messages are categorized by severity (and verbosity), with errors being the most severe, then warnings, informational messages, debug messages and verbose messages being the least severe. Each type of logging message has its own method. Simply call the method and a log message is created. The message types, and their related method calls are:
- The Log.e() method is used to log errors.
- The Log.w() method is used to log warnings.
- The Log.i() method is used to log informational messages.
- The Log.d() method is used to log debug messages.
- The Log.v() method is used to log verbose messages.
- The Log.wtf() method is used to log terrible failures that should never happen. («WTF» stands for «What a Terrible Failure!» of course.)
The first parameter of each Log method is a string called a tag. It’s common practice to define a global static string to represent the overall application or the specific activity within the application such that log filters can be created to limit the log output to specific data. For example, you could define a string called TAG, as follows:
You will often find that the tag is defined as the class in which the Log statement occurs. This is a reasonable convention, but anything identifiable or useful to you will do.
Now anytime you use a Log method, you supply this tag. An informational logging message might look like this:
You can also pass a Throwable object, usually on Exception, that will allow the Log to print a stack trace or other useful information.
NOTE: Calling the Log.wtf() method will always print a stack trace and may cause the process to end with an error message. It is really intended only for extreme errors. For standard logging of exceptions, we recommend using the Log.e() method. The Log.wtf() method is available only in Android 2.2 or later. The rest are available in all versions of Android.
Step 3: Adding Log Support to an Activity Class
Now let’s add some logging to your Activity class. First, add the appropriate import statement for the logging class android.util.Log. Next, declare a logging tag for use within your class (or whole application); in this case, we call this variable DEBUG_TAG. Finally, add logging method calls wherever you want logging output. For example, you might add an informational log message within the onCreate() method of your Activity class.
Below is some sample code that illustrates how all these steps come together:
Step 4: Monitoring Application Log Output – The Easy Way
You can use the LogCat utility from within Eclipse to view the log output from an emulator or device. LogCat is integrated into Eclipse using the Android Development plug-in. You’ll find the LogCat panel integrated into the DDMS and Debug perspectives of Eclipse.
Step 5:Monitoring Application Log Output – Creating Log Filters
As you can see, the basic LogCat logging output includes log data from lots of different sources. For debugging purposes, it can be useful to filter the output to only the tags for your specific application. This way, you can focus on your application log output, amidst all the clutter.
You can use the LogCat utility from within Eclipse to filter your log messages to the tag string you supplied for your application. To add a new filter, click the green plus sign button in the LogCat pane of Eclipse. Name the filter—perhaps using the tag name—and fill in the tag you want to filter on. A new tab is created in LogCat that will show only log messages that contain this tag. You can create filters that display items by severity level.
Performance Considerations with Logging
Logging output puts a damper on application performance. Excessive use can result in decreased application performance. At minimum, debug and verbose logging should be used only for development purposes and removed before release. It’s also a good idea to review other logging output before publication as well.
Conclusion
Logging is a very handy debugging and diagnostic technique used by developers. Use the logging class provided as part of the Android SDK to log important information about your application to LogCat, but make sure you review your application’s logging implementation prior to publication, as logging has performance drawbacks.
Источник
Debugging and Logging Android App
Introduction
In this post, I will tell you all android logging library and debugging tool. Logging android app helps you to debug a bug and exception in local or remote. It can be production and development environment. Few things you can logging android studio
Requirements
In development mode, you are always faced errors, exceptions, and crashes. It can be tracked by android logging system or Logcat. When it’s come in production app, it not easy to debug because in the users’ device can be so many reasons for any mishappening, such as low network connectivity, device configuration, memory, CPU uses etc. I will tell you all android logging library and debugging tool that help you to find out real problem local and remote as well
Crashes and exceptions can be logged local and remote server as well. Debugging & Logging android app is compulsory to build a pro android application.
Major problem in android app development
- You can not check & view shared preference variables – View the shared preference and local database is not easy in android studio.
- For logging (standard logging) always need to give tags. Basically, In a big team follow the same logging standard by all developers is not easy. I will discuss some libraries that provide a centralized logging system in all app.
- Remotely view logs for all devices – We can debug and log locally, mean those are connected in Android Studio via USB debugging. Android logging system does not provide remote logging solution.
- Database access is very difficult – Check the database data little bit tricky in android app development
- Inspect elements – Inspect all element and network call is not easy and trackable
Following most debugging tools and libraries for logging android app
- Bugfender
- Android Debug Database
- Fabric Crashlytics (Firebase) & Answer
- Stetho
- Timber
1. Bugfender
The remote logging system for iOS and Android application. Bugfender is a best for remote logging android app. You can log each event with a custom parameter in an orgenized way. You can easily debug what went wrong of user device using logging android
Why Bugfender? At the time of development
- Logs from many devices required.
- Not possible to attach all the devices with the development machine.
- Need to check some special values on some events fire.
- The log will be saved on cloud and log file can be downloaded as well.
Features
- Logged all remote devices logs.
- You can setup cloud-based logging.
- Bugfender provides free version provides last 24 hours logs.
- Shows different logs for different devices.
- One can enable/disable devices as well as logging on those devices.
- Have different methods to print UI logs, all events logs(complete Android system logs).
- The developer can log only particular event logs.
2. Fabric Crashlytics (Firebase)
For all types crash ‘Fabric’s Crashlytics’ provide a solution for that. Fabric’s SDK logged all crashes and exceptions remotely with user device configuration
Benefits:
- Able to log errors and exception an complete stack trace for remote devices
- Gives log for debug as well as for production environment.
- It provides all details of device models.
- All the crashes and exceptions will be notified via email, every time they occur.
- Crashes reported automatically.
- To log caught exceptions crashlytics.logException(exception);
- We provide some key-value pair for more reference of exception.
Limitations
- Sometimes didn’t get complete context of a class where an error occurs.
- Android logs for crashes are sometimes difficult to understand.
3. Stetho
Stetho is mainly a debugging and logging library for Android apps. It developed by Facebook. It uses Chrome’s Developer tool to display debugging data of apps. You can debug all things in local using logging android app.
Features provided:
- View Hierarchy
- Database inspection
- Shared Preferences
- JavaScript Console
- Dumpapp
2.1 View Hierarchy: Able to view all the View elements and detailed properties (styles). The user will have a complete hierarchy view of layout including layouts which were integrated at runtime.
2.2 DataBase Inspection: User views complete database tables and also able to do the query for some specific data and also alter the data directly from here.
2.3 Shared Preferences: User can view all the shared preferences variables and also changes these values.
2.4 Network Inspection: User can view all the network request and JSON response, image preview of application.
2.5 JavaScript Console: User can interact with the application and even Android SDK by executing javascript code in the console.
2.6 Dumpapp: Provided command line interface for the Android application.
Integration: Follow the below link
User runs the code, He will see request and response in the ‘Network’ tab of Developers tool.
Inspection Process- You have done with all integration steps than move to chrome browser
- Open chrome browser in the developer system.
- Navigate to ‘chrome://inspect’.
- Here user will find all the connected devices with the Application name.
- Click ‘inspect’ to start the inspection.
4. Timber’s Requirement:
Timber is a logging library that manage all log in organised way logging android studio.
- Do not require to specify ‘TAG’ for class context like ‘Android log system. Its timber’s inbuilt feature.
- Can control which kind of logs want to show in crashlytics. eg. errors and exceptions. It will not show ‘info’ and ‘warnings’ log in crashlytics.
- We can print line-number as well with the logs.
- Provide all logging methods, provided by ‘Android logging system’. Like, debug, info, error, wtf etc
Integration:
- Follow the timber integration instruction
- Add the following in-app level Gradle file
- In Application, class add below code
Now timber provides all kind of logging eg. debug, info, verbose etc in ‘Developer tool’s console’. Do not need to add ‘TAG’, just add messages where ever it is required.
Limitations
- Do not work for remote devices.
- Logging can’t be saved.
5. Android Debug Database
This android logging library allows you to view databases & shared preferences in your development machine browser.
Features
- View database.
- Run sql query to modify or delete data from DB.
- View/edit/delete shared preferences of application.
- Directly edit the database values.
- Search and sort data.
- Download database.
Limitations
- Development machine & device should be in the same network.
Integration: Follow the link
Источник