Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

Android에서 Timber 라이브러리로 로깅 경험 향상하기

안드로이드 앱을 개발하다 보면 디버깅과 상태 추적을 위해 로그(Log)를 활용하는 일이 매우 빈번합니다. 대부분의 개발자는 기본 제공되는 android.util.Log를 사용하지만, 이 방식에는 한 가지 고민거리가 있습니다. 바로 릴리즈(배포) 빌드에서 불필요한 로그까지 출력된다는 점입니다.

Timber는 Jake Wharton이 만든 안드로이드 전용 로깅 라이브러리로, 이러한 문제를 깔끔하게 해결해 줍니다. Timber를 사용하면 태그(tag)를 일일이 지정할 필요 없이 자동으로 생성해 주고, 디버그/릴리즈 빌드에 따라 로그 출력 여부를 손쉽게 제어할 수 있습니다.

이 글에서는 Timber를 안드로이드 프로젝트에 통합하고 사용하는 방법을 단계별로 살펴보겠습니다.

1단계: 새 프로젝트 생성

Android Studio에서 File → New Project를 선택하고, 필요한 정보를 모두 입력하여 새 프로젝트를 생성합니다.

2단계: build.gradle에 Timber 의존성 추가

앱 수준의 build.gradle 파일에 아래와 같이 Timber 라이브러리를 추가합니다.

apply plugin: 'com.android.application'
android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.example.andy.myapplication"
        minSdkVersion 15
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    implementation 'com.jakewharton.timber:timber:4.7.1'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

3단계: MainActivity에서 Timber 초기화

Timber는 사용하기 전에 반드시 초기화(plant)해야 합니다. 일반적으로 MainActivityonCreate() 메서드에서 디버그 빌드일 때만 DebugTree를 심어(plant)줍니다.

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import timber.log.Timber;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (BuildConfig.DEBUG) {
            Timber.plant(new Timber.DebugTree());
        }
    }
}

이렇게 하면 릴리즈 빌드에서는 로그가 출력되지 않으므로, 배포 시 로그를 일일이 삭제하는 번거로움 없이 깔끔한 코드를 유지할 수 있습니다.

4단계: Timber의 다양한 로그 메서드

Timber는 기존 Log 클래스처럼 로그 우선순위별 메서드를 제공합니다.

Timber.v("Some Text"); // VERBOSE(상세) 로그
Timber.d("Some Text"); // DEBUG(디버그) 로그
Timber.i("Some Text"); // INFO(정보) 로그
Timber.w("Some Text"); // WARN(경고) 로그
Timber.e("Some Text"); // ERROR(오류) 로그

5단계: Timber 실전 예제

디버그 빌드와 릴리즈 빌드에 따라 서로 다른 Tree를 심는 완전한 예제 코드입니다.

package com.example.andy.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import timber.log.Timber;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (BuildConfig.DEBUG) {
            Timber.plant(new Timber.DebugTree());
        } else {
            Timber.plant(new ReleaseTree());
        }

        Timber.v("Some Text");
        Timber.d("Some Text");
        Timber.i("Some Text");
        Timber.w("Some Text");
        Timber.e("Some Text");
    }
}

위 예제에서는 디버그 빌드에서는 DebugTree를, 릴리즈 빌드에서는 커스텀 ReleaseTree를 심습니다. 이렇게 하면 릴리즈 환경에서도 크래시 리포트 등 필요한 로그만 선택적으로 수집할 수 있습니다.

6단계: 뷰와 매니페스트 수정

이 예제에서는 화면(UI)이나 AndroidManifest.xml 파일을 별도로 수정할 필요가 없습니다.

실행 결과

위 코드를 실행하면 Logcat에 아래와 같은 로그가 출력됩니다.

Android에서 Timber 라이브러리로 로깅 경험 향상하기

마무리

Timber를 사용하면 태그 자동 생성, 빌드 타입별 로그 제어, 문자열 포매팅 등 기본 Log 클래스보다 훨씬 편리한 로깅 환경을 구축할 수 있습니다. 특히 릴리즈 빌드에서 로그를 자동으로 숨길 수 있어, 배포 전 로그 정리 작업에서 완전히 해방될 수 있다는 점이 가장 큰 장점입니다.