Что такое timber android

Простая и очевидная замена android.util.Log

Однажды я писал один проект. Проект выдался большим и писал я его долго.
Там было все что только можно было запихнуть — и retrolambda/java8, и пара десятков
других библиотек (жадность заказчика до новых фич не знала границ, а потому
росло число зависимостей).

Но речь даже не об этом. Настало время делать релиз. И оказалось что в проекте
множество логов и неплохо бы их из релизной сборки убрать. Всем известный
способ с ProGuard не сработал с первого раза. С каждым новым «-keep»
приложение падало в каком-то новом месте. Так что ProGuard пришлось отключить
до лучших времен.

Все это время меня не покидало ощущуение, что управление уровнем логировния c
помощью изменения байт-кода — это нелепо. И тогда за полчаса я написал свой
примитивный логгер.

Обычно я редко довожу свои проекты до конца, но тут он был настолько прост — что теперь он лежит на гитхабе, желающие — пользуйтесь.

Совместимое API — залог простой миграции

Одна из причин почему я не стал использовать Timber — потому что мои пальцы
привыкли печатать Log.d. Свой класс я назвал тоже «Log», а методы сделал совместимыми с «android.util.Log».

Это значит, что если вы захотите соскочить со стандартного логгера — просто
замените импорты. Это можно сделать с помощью sed, или с помощью вашей любимой
IDE.

А в чем преимущество?

Ну вот несколько отрывков кода, показывающие основные фичи логгера:

Уговорили, где взять?

В build.gradle библиотека подключается как обычно:

Вот так можно заменить импорты:

Логгер под лицензией MIT, используйте на здоровье. Там один класс без
зависимостей, всего на 250 строк, так что проект ваш тяжелей/тормозней не станет.

Любые пожелания или багрепорты (особенно с патчами) приветствуются!

Источник

Timber : A step towards better Logging

Logging is one of the most used utility in android framework. It is really helpful in debugging your code when debugging by break-point just wont work. It is generally a good practice to place Log statements in your code as it helps you keep a track of flow control in your application. Similarly, it is not a recommended to have log statements in your release ready code, since those log statements can be read by anyone who connects his phone to a PC. So, when releasing your application to the play store, it is recommended to remove all the log statements from your code.

But this can be a real pain. There are so many log statements all over your code and now you have to manually find each one and remove it from your code just for the release version.

Another problem with the default logging mechanism is that you need to pass the TAG, every time you write a log statement.

Wouldn’t it be wonderful if the log statements would automatically disable themselves when in production? Wouldn’t it be great if the Log statements automatically picked up the TAG/classname while logging and you could just focus on writing better code?

Well, problems such as these and many more are solved by a better logging library in android, called Timber (by Jake Wharton).

Читайте также:  Witch hunter trainer андроид последняя версия

It is a light-weight, easy to use library which takes care of most of the maintenance you need to do while logging so that you can focus more on writing great code and less on the maintenance stuff.

Let’s go ahead and create a sample application to see how you can include Timber in your android application and make your logging life easier.

Getting Started

We will be creating a simple android application with 4 buttons. Each button would print out different priority log statement on the console.

Create a new project in Android and add a dependency for Timber in your app level build.gradle file. At the time of this writing, this is the latest dependency version for timber:

Initializing Timber

With the dependency downloaded, now it’s time to initialize the timber library. Best place to initialize timber is in the Application class which will be active during the entire lifetime of the application. So, let’s create a custom application class and initialize our Timber library in it:

Creating MainActivity

Let’s now create our MainActivity by adding 4 buttons and setting on click listeners to each of them. Here is my activity_main.xml file. I’m using ConstraintLayout as my root layout and including 4 buttons each for different logging levels.

Now it’s time to set click listeners to these buttons and print a log statement every time a button is clicked. I’m using kotlin’s synthetic bindings instead of regular findViewById calls or Butterknife. Here is my MainActivity.kt file:

Notice how we didn’t need to initialize any TAG variable in our class, Timber does it automatically for you.

Customizing Timber for Debug and Release

Now, this is where Timber really shines. What we’ve done till now was nothing great, just printing the log statements on button clicks. But as you know, logging in production is not a good idea, so now we will write code to disable the logs for production while keeping them enabled during debug mode.

We’ll write a if block to check if our app is in debug mode and enable logging for that, if not, then we want to initialize Timber using a custom tree.

Here’s the modified MainApplication.kt class:

As you can see, we’ve initialized timber using a custom ReleaseTree when in release mode. Now let’s go ahead and create our own release tree.

Creating a Custom Tree

Creating a release tree is fairly simple. Create a new Kotlin class and extend it from Timber.Tree. Implement all the abstract functions and you’re good to go.

Here’s my ReleaseTree.kt:

As you can see, whenever there is an error, we can send the log to an online service such as Firebase CrashAnalytics or Crashlytics and not logging out on production.

Result

Benefits of using Timber vs Android Logging

Let’s look at some of the benefits of using Timber library instead of the default Log utility by android sdk.

  • No need to worry about TAGS: Timber generates the TAGs automatically for you so you don’t have to worry about including a global TAG in every class.
  • No need to manually remove Log statements: As already shown, it’s really easy to disable Logging for release apps. Hence, you no more have to go through your entire code and manually remove all the logs.
  • Customized behavior on production: In production versions you don’t want to log, although you definitely want to log any crashes that might occur. You can implement this by using a custom debug tree (as shown above) which instead of logging to the logcat, sends the logs to your crashlytics service.
  • Customized Meta-Data: You can include customized meta data with your log statements. For example: I’ve added class name, line number and method name from which the log statement is getting printedi n the implementation above. Having this data at your disposal can make debugging easier.
  • Lightweight: Does’t not increase your app size/method count by much. Really lightweight library as it is just a wrapper over the already existing log utility.
Читайте также:  Tips андроид что это

Conclusion

For long I had ignored the use of log statements and printing out better logs, but as my code got bigger and problems got complex, I realized I needed to adopt better and more efficient debugging routines and hence, using Timber is one step in the right direction.

*Important*: I’ve created a SLACK workspace for mobile developers where we can share our learnings about everything latest in Tech, especially in Android Development, RxJava, Kotlin, Flutter, and overall mobile development in general.

Like what you read? Don’t forget to share this post on Facebook, Whatsapp, and LinkedIn.

You can follow me on LinkedIn, Quora, Twitter, and Instagram where I answer questions related to Mobile Development, especially Android and Flutter.

If you want to stay updated with all the latest articles, subscribe to the weekly newsletter by entering your email address in the form on the top right section of this page.

Источник

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.

Читайте также:  Cwm recovery all android

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 :

Источник

Android Better Logging using Timber Library

Timber is a logging utility class built on top of Android’s Log class. While in development, we usually end up writing lot of log statements and before the release, we’ll cleanup the log statements by removing them manually (even though logs can be disabled in release build). This tedious process can be avoided easily by using Timber.

Timber provides lots of other options as well. Let’s see how it can be used in our projects to maintain the logs better.

1. Timber

Below are few debug statements printed using default Log class.

The above same statements can be printed using Timber as below.

  • You can notice here, the TAG is not passed to Timber as it automatically detects the class in which logs were written.
  • Also String formatter is not used to format the statement as Timber can do it automatically for you.

2. Integrating Timber

Now let’s see how to integrate Timber library in your project making it available in every class.

1. Create a new project in Android Studio from File ⇒ New Project and select Basic Activity from templates.

2. Open build.gradle and add Timber dependency. Butterknife is optional here, but required for this example.

3. Timber has to be initialized as soon as app starts. So, Application class would be best place to do that. Create new class named MyApplication.java and extend the class from Application.

  • Initialize Timber in onCreate method by planting a new Tree.
  • Here Timber.DebugTree() prints logs in debug mode.
  • If you want to catch exceptions in release mode, you can create a different Tree and plant it in release mode. This step is completely optional but if you want to send exceptions to a different service, this is the appropriate place to do it.

4. You can create a custom tree by extending the class from Timber.Tree. Here is the example of ReleaseTree.java class.

4. Finally add MyApplication to your tag in your AndroidManifest.xml

5. Now, Timber is ready to use in your app. Below are few examples of Timber log statements demonstrating different scenarios.

Hi there! I am Founder at androidhive and programming enthusiast. My skills includes Android, iOS, PHP, Ruby on Rails and lot more. If you have any idea that you would want me to develop? Let’s talk: [email protected]

Источник

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