Skip to main content

Android Logging using Timber Library

 


Timber  is a logger with a small, extensible API which provides utility on top of Android's normal Log class.

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.

int a = 100;
Log.e("TAG", String.format("Integer a value is: %d", a));
 
String name = "Android Codest";
Log.e("TAG", String.format("Find source from: %s", name));

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

int a = 100;
Timber.d("Integer a value is: %d", a);
 
String name = "Android Codest";
Timber.d("Find source from: %s", name);

You can notice here, the TAG is not passed to Timber
as it automatically detects the class in which logs were written. Also String formatted 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.


build.gradle
// timber
implementation 'com.jakewharton.timber:timber:4.7.1'

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.

MyApplication.java
package com.androidcodest.timber;
 
import android.app.Application;
 
import com.androidcodest.timber.log.ReleaseTree;
import timber.log.Timber;
 
public class MyApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
 
        if (BuildConfig.DEBUG) {
            Timber.plant(new Timber.DebugTree());
        } else {
            Timber.plant(new ReleaseTree());
        }
    }
}

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

ReleaseTree.java
package com.androidcodest.timber.log;
 
import android.util.Log;
 
import timber.log.Timber;
 
public class ReleaseTree extends Timber.Tree {
    @Override
    protected void log(int priority,
String tag, String message, Throwable t) {
 if (priority == Log.VERBOSE || priority == Log.DEBUG) {
            return;
        }
 
       
    }
}

4. Finally add MyApplication to your <application> tag in your AndroidManifest.xml

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
    package="com.androidcodest.timber">
 
    <application
        android:name=".MyApplication"
        ...>
 
    </application>
 
</manifest>

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

MainActivity.java
package com.androidcodest.timber;
 
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.widget.Toast;
 
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import timber.log.Timber;
 
public class MainActivity extends AppCompatActivity {
 
    private Unbinder unbinder;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        unbinder = ButterKnife.bind(this);
 
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
 
        // boolean
        boolean isWeekend = false;
        Timber.d("The boolean value. Is weekend: %b", isWeekend);
 
        // integer
        int a = 100;
        Timber.d("Integer a value is: %d", a);
 
        // float
        float pi = 3.14159f;
        Timber.d("Pi value is: %f", pi);
    }
 
    @OnClick(R.id.btn_log_string)
    void logMessage() {
        Timber.d("Hello from Timber!");
 
        showToast();
    }
 
    @OnClick(R.id.btn_log_exception)
    void logException() {
        try {
            int a = 10 / 0;
            Timber.d("Value of a: %d", a);
        } catch (Exception e) {
            Timber.e(e);
 
            // or //
 
            Timber.e("Exception in math operation: %s",
e.getMessage());
        }
 
        showToast();
    }
 
    private void showToast() {
        Toast.makeText(getApplicationContext(),
"Check LogCat for message or error!", Toast.LENGTH_SHORT).show();
    }
 
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
    }
}

That's all folks !!

Comments

Popular posts from this blog

Convert your apk into Android App Bundle

Android App Bundle In Google I/O 2018, a new publishing format has been introduced for Android applications called Android App Bundle. It is a new upload format that includes all your app’s compiled code and resources, but defers APK generation and signing to Google Play. Traditionally, Android apps are distributed using a special file called an Android Package(.apk). How to build an app bundle? You can easily build your app bundle using Android Studio(3.2 Canary 14+) or using command line interface. The generated app bundle will be stored at app/build/outputs/bundle/buildVariant/bundle.aab. Android Studio : Go to Build > Build Bundle(s)/APK(s) and select Build Bundle(s). Console : ./gradlew bundle Dynamic Delivery with Split APKs A fundamental component of Dynamic Delivery is the split APK mechanism available on Android 5.0 (API level 21) and higher. Split APKs are very similar to regular APKs — they include compiled DEX bytecode, resources, and an Android manifest. However, the ...

Push Notification using Firebase in Android

This is a tutorial about sending push notifications to Android through Firebase, based on the new release of Firebase this year (2016). This tutorial shows how to setup the skeleton for sending and receiving push notifications via FCM with instructions on server code. 1. Get started Add a new project or import an existing project to  Firebase console . If you choose to create a new project, you need to set the project name and country. For example, I will call my project Firebase Notification Then select "Add Firebase to your Android app". Set a package name for your app. I only set my package name and omit the SHA-1 because I don't use Firebase for my app's authentication. Click the  ADD APP  button here to download google-services.json. This is an important file and you will need to put it into your app. 2. Add google-services.json to your app folder Replace the google-services.json in your app folder. The Google services plugi...