Android logging best practices

Better Logging In Android Using Timber

While developing android applications we as developers tend to put in a lot of logs with in different different priorities for this sake android sdk comes in with a utility class Log, which does have utility methods to log our messages with different priorities the most common methods that we use for different cases like we uses Log.e(TAG,”message”) in the cases we want to show some error (this usually appears in red color in the logcat window of android studio), or Log.d(TAG, «message») when we want to print some message for the purpose of debugging, like value of some data.

Usually when the application development is completed and its the time to release the app on the play store, we need to remove all Log statement from the app, so that none of the application data such as user information, hidden application data, auth-tokens are available to user in logcat as plain text and this becomes a cumbersome task

There are several ways to tackle this problem

1. Condition based logging

In this we can make a public static boolean variable in Application class like in the below code snippet.

and use this variables value as check for logging like the code snippet below

and use this boolean variable at every place where you want to put a log message, and once you are ready to release the app, just set isDebug = false in the application class, but this approach puts in an extra line of code, which is completely unnecessary and can be avoided.

This simply can be achieved using android’s in built build configuration, BuildConfig. DEBUG can be used instead of that boolean variable for checking if the build type is release or debug.

2. ProGuard

This approach is all also a solution to this problem, you can render the Log class ineffective and can remove those statement in the release build by putting in

into the proguard rules file.

Here comes Timber, the best solution to tackle this problem

What if I tell you there exists a simple library called “Timber” which can log your messages and gives you the control over the flow of logs. Timber is a yet another cool library developed by an awesome developer Jake Wharton.

Adding timber to you project

To add timber to your android studio project, just paste in the below line in to /app/build.gradle file and sync the project.

Once the project is synced just plant a timber debug tree in the Application class, because as per the instruction on Timber’s github page and I quote it

Installation of Tree should be done as early as possible. The onCreate of your application is the most logical choice.

Here, Timber.DebugTree() prints the logs when your application type is debug application.

And that’s all we need to do in order to use timber. Wherever you have used that Log…(…) statement just remove that tag parameter and replace Log with Timber.

as you can see in the above gist, that it is not required to pass in the tag parameter in the Timber.d(. ) or Timber.e(. ) statement, as Timber automatically detects the class in which logs were written.

But there might me requirement when you need to specify a custom tag which can be simply achieved by

as shown in the above gist. More about Timber can be found at :

Источник

Best practices for Android Logging

Android System offers to developers a centralized system to manage all logs. Each developer can write custom log messages in his application that will be visible in the centralized system. Each log message has an associated tag and a priority constant. Thus, you can filter log statements from the centralized logs system easily.

Читайте также:  Камера для андроид посоветуете

API for sending logs in Android is based on the class android.util.Log . This class offers you the following static methods :

  • Log.v() for a VERBOSE priority log message
  • Log.d() for a DEBUG priority log message
  • Log.i() for an INFO priority log message
  • Log.w() for a WARN priority log message
  • Log.e() for an ERROR priority log message
  • Log.wtf() for a What a Terrible Failure message. A condition that should never happen

The order in terms of verbosity, from least to most is ERROR, WARN, INFO, DEBUG then VERBOSE. Be aware that Verbose priority should never be compiled into an application except during development phase. Debug logs are compiled in but stripped at runtime. Error, Warning and Info logs are always kept at runtime.

1/ Write a log statement

Best practice when you can to write a log statement is to define a TAG constant to filter easily these logs later :

Then, you can write your log message with your desired priority like that :

2/ Viewing a log statement

To view system logs from a device, you must use the logcat tool provided by the Android SDK. Most used IDE like Android Studio or Eclipse ADT offers you dedicated views. You can then filter by tag or package for example.

3/ Remove logs for an application in production

For an application in production, you mustn’t have any log statements. To enable your logs statements calls only during development phase, Android offers you the BuildConfig.DEBUG property. This flag is setted automatically to false when an application if deployed into an APK for production and then, it’s setted to true during development.

To use it, you must write your log statements like that :

Источник

Логирование в 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 LogCat And Logging Best Practice

android.util.Log is the log class that provides the log function. It provides the below methods to log data into the LogCat console.

1. Android Log Methods.

  1. Log.v(): Print verbose level log data. The verbose level is the lowest log level, if you print so much this kind of log data, it is not meaningful.
  2. Log.d(): Print debug level log data. Debug level is one step higher than verbose level. Debug log data is usually useful in android application development and testing.
  3. Log.i(): Print info level log data. Info level is one step higher than debug level. Info log data is used to collect user actions and behaviors.
  4. Log.w(): Print warn level log data. Warn level is one step higher than info level. When you see this kind of log data, it means your code exists potential risks, you need to check your code carefully.
  5. Log.e(): Print error level log data. Error level is the highest level. It is always used in java code catch block to log exception or error information. This kind of log data can help you to find out the root cause of app crashes.
Читайте также:  Viber android нет звука

2. Android Log Methods Example.

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/ciBUMesUfVo

  1. This example is very simple. When you click the button, it will print above 5 kinds of log data in the LogCat console.
  2. When you input the search keyword LogActivity in the LogCat panel, the app log data will be filtered out. For each line of log data, there are the log time, class name, and log message.
  3. You can also filter out the log data by it’s type, verbose, info, debug, warn, or error. This can make log data search more easily and accurately, you can see the below demo video.

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/zyUvmTF_Mzw

  1. Click the Settings icon in the LogCat panel, you can configure which column to be displayed for each line of the log.
  2. The columns include Show date and time, Show process and thread IDs(PID-TID), Show package name, Show tag, you can see it in the below picture.

Источник

Best Practices for Android Logging and Testing

As a developer, it is not necessary to do logging and testing at all if you are not aiming for a quality app. However, it is logging, testing and debugging that make the difference. To achieve the highest of quality, sometimes the testing phase takes more resources than the development itself and, more surprisingly, this is justifiable considering the positive impact of testing on the app quality and more importantly user experience.

Logging is essential to get enough data about the behavior of an app on different types of devices to debug the app when it faces an issue. Following are some smart logging practices that expert programmers use to get the most effective and accurate results in resource efficient manner.

  • Using a 3 rd party logging framework is highly recommended because of its various advantages. Android’s own logging system works great but its features are limited. On the other hand, a separate logging framework is a much more flexible solution that allows developers to change the behavior of logging according to their preferences.
  • Make sure you have the full control over the logging because not everyone wants to see the logs and it is unnecessary as well as waste of resources to log everything. Reducing the amount of logging to an appropriate level is a smart move.
  • The logging system might not be as secure as you think. In some cases, logging systems leak sensitive data, so be careful with such information. Sensitive data refers to email addresses, users’ location, passwords and other private information.
  • Remote testing tools like Bugfender have changed the way developers do testing and debugging. Remote testing has tons of advantages over traditional testing. Let’s take a closer look.

Remote logging is completely safe if there is encryption when communicating to the centralized server. These tools are designed to focus on the relevant data and ignore or mask all kinds of personal data and information while logging. In most of the cases, the tool does not even have access to the data. Remote testing allows users to test any feature whenever they want. As the apps are designed to send the logs to server automatically, developers and testers can check them whenever and from wherever they want.

Читайте также:  Android studio rotate image

Be A Superhero

Fend off bugs and keep your users safe.

Bugfender is a highly configurable tool where users can control the devices they want to monitor. For example, if a nasty bug is only occurring on specific devices and the app runs perfect on other devices then developers can turn off logging on device where it is unnecessary. Using remote testing tools for logging and debugging is different than using physical devices for testing.

With remote testing, developers can monitor hundreds of devices simultaneously and analyze their logs to find the culprit. This approach is not only drastically cost efficient, but also reduces the time required for testing an app. Although the mechanism, technologies and protocols used in remote testing tools are sophisticated piece of engineering yet they are extremely easy to install and set up for the first time.

Within minutes you can install the tool and set up your remote lab from where you can test your app on real devices. One of the greatest benefits of it is continuous testing; development and testing are evolutionary phases where developers need to introduce new features and performance improvements every once in a while to keep their apps up to date with the market. For example, Apple enforces developers to update their apps after few months if an important bug is found, otherwise they would be removed from the App Store.

Centralized data and logs help developers and testers prioritize the issues based on their severity and number of users facing them. For example, an Android app has an issue that is associated with Samsung Galaxy Note 4 and another issue that is associated with Google Galaxy Nexus. Now suppose, 80% of the users are using Samsung Galaxy Note 4 and 10% are using Google Galaxy Nexus. It is pretty obvious that developers need to prioritize the issue associated with devices that have a bigger market share.

In the case of testing on physical devices, your capacity of testing is limited by the resources you can spend on buying devices and testing servers, and keeping up with the newest ones. For example, you cannot run tests on multiple devices simultaneously because of limited number of computers, USB ports and performance. On the other hand, remote testing does not have such limitations and the process is fully automated.

How is Bugfender a Game-Changer in Logging and Debugging?

It is a common practice to use logging during the development phase as apps in production phase do not need logging at all. The reason is quite simple; end users don’t need logs, they don’t know what to do of them and most importantly it is unnecessary waste of storage space with log files. Now, the real problem is how would developers be able to find issues that occur only on specific models?

That’s where Bugfender comes in action; it is specifically designed to help developers test their apps on real devices after the release, find the bugs before users do and fix them in the next version. Android and iOS fragmentation has made it difficult for developers to test their apps on real devices and reproducing a bug in the lab is almost impossible.

Bugfender sends the logs to centralized server where users can analyze the abnormal behavior of apps on specific devices and find the root cause of that. There are many crash reporting tools available for iOS and Android development but not all bugs result in crash or failure. Bugfender does not solely rely on crashes but instead records everything. Interestingly, you can remotely turn on/off the logging feature on specific devices to reduce the volume of logs.

Источник

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