-->

[Android / Java]

심플한 Log TAG 설정

 

(부제 : TAG 이름을 하드 코딩하면 안 되는 것이냐고 오)

StackOverFlow에서 재밌는 글을 발견했다. 

항상 로그 찍을 때 사용하는 TAG에 관련한 글이었다.

stackoverflow.com/questions/11239882/why-use-tag-in-most-of-the-android-logging-code/41584221

 

Why use TAG in most of the Android logging code

I can see this is common practice among Android developers. public final class TasksSample extends ListActivity { private static final String TAG = "TasksSample"; private void method() { ...

stackoverflow.com

 

먼저 안드로이드 스튜디오에서 로그를 찍으려면 파라미터가 여러 개 필요하다. 

Log Class를 한번 훔쳐보자.

/*
 * Copyright (C) 2006 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.util;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.UnknownHostException;

/**
 * Mock Log implementation for testing on non android host.
 */
public final class Log {

    /**
     * Priority constant for the println method; use Log.v.
     */
    public static final int VERBOSE = 2;

    /**
     * Priority constant for the println method; use Log.d.
     */
    public static final int DEBUG = 3;

    /**
     * Priority constant for the println method; use Log.i.
     */
    public static final int INFO = 4;

    /**
     * Priority constant for the println method; use Log.w.
     */
    public static final int WARN = 5;

    /**
     * Priority constant for the println method; use Log.e.
     */
    public static final int ERROR = 6;

    /**
     * Priority constant for the println method.
     */
    public static final int ASSERT = 7;

    private Log() {
    }

    /**
     * Send a {@link #VERBOSE} log message.
     * @param tag Used to identify the source of a log message.  It usually identifies
     *        the class or activity where the log call occurs.
     * @param msg The message you would like logged.
     */
    public static int v(String tag, String msg) {
        return println(LOG_ID_MAIN, VERBOSE, tag, msg);
    }

    /**
     * Send a {@link #VERBOSE} log message and log the exception.
     * @param tag Used to identify the source of a log message.  It usually identifies
     *        the class or activity where the log call occurs.
     * @param msg The message you would like logged.
     * @param tr An exception to log
     */
    public static int v(String tag, String msg, Throwable tr) {
        return println(LOG_ID_MAIN, VERBOSE, tag, msg + '\n' + getStackTraceString(tr));
    }

    /**
     * Send a {@link #DEBUG} log message.
     * @param tag Used to identify the source of a log message.  It usually identifies
     *        the class or activity where the log call occurs.
     * @param msg The message you would like logged.
     */
    public static int d(String tag, String msg) {
        return println(LOG_ID_MAIN, DEBUG, tag, msg);
    }

    /**
     * Send a {@link #DEBUG} log message and log the exception.
     * @param tag Used to identify the source of a log message.  It usually identifies
     *        the class or activity where the log call occurs.
     * @param msg The message you would like logged.
     * @param tr An exception to log
     */
    public static int d(String tag, String msg, Throwable tr) {
        return println(LOG_ID_MAIN, DEBUG, tag, msg + '\n' + getStackTraceString(tr));
    }

    /**
     * Send an {@link #INFO} log message.
     * @param tag Used to identify the source of a log message.  It usually identifies
     *        the class or activity where the log call occurs.
     * @param msg The message you would like logged.
     */
    public static int i(String tag, String msg) {
        return println(LOG_ID_MAIN, INFO, tag, msg);
    }

    /**
     * Send a {@link #INFO} log message and log the exception.
     * @param tag Used to identify the source of a log message.  It usually identifies
     *        the class or activity where the log call occurs.
     * @param msg The message you would like logged.
     * @param tr An exception to log
     */
    public static int i(String tag, String msg, Throwable tr) {
        return println(LOG_ID_MAIN, INFO, tag, msg + '\n' + getStackTraceString(tr));
    }

    /**
     * Send a {@link #WARN} log message.
     * @param tag Used to identify the source of a log message.  It usually identifies
     *        the class or activity where the log call occurs.
     * @param msg The message you would like logged.
     */
    public static int w(String tag, String msg) {
        return println(LOG_ID_MAIN, WARN, tag, msg);
    }

    /**
     * Send a {@link #WARN} log message and log the exception.
     * @param tag Used to identify the source of a log message.  It usually identifies
     *        the class or activity where the log call occurs.
     * @param msg The message you would like logged.
     * @param tr An exception to log
     */
    public static int w(String tag, String msg, Throwable tr) {
        return println(LOG_ID_MAIN, WARN, tag, msg + '\n' + getStackTraceString(tr));
    }

    /*
     * Send a {@link #WARN} log message and log the exception.
     * @param tag Used to identify the source of a log message.  It usually identifies
     *        the class or activity where the log call occurs.
     * @param tr An exception to log
     */
    public static int w(String tag, Throwable tr) {
        return println(LOG_ID_MAIN, WARN, tag, getStackTraceString(tr));
    }

    /**
     * Send an {@link #ERROR} log message.
     * @param tag Used to identify the source of a log message.  It usually identifies
     *        the class or activity where the log call occurs.
     * @param msg The message you would like logged.
     */
    public static int e(String tag, String msg) {
        return println(LOG_ID_MAIN, ERROR, tag, msg);
    }

    /**
     * Send a {@link #ERROR} log message and log the exception.
     * @param tag Used to identify the source of a log message.  It usually identifies
     *        the class or activity where the log call occurs.
     * @param msg The message you would like logged.
     * @param tr An exception to log
     */
    public static int e(String tag, String msg, Throwable tr) {
        return println(LOG_ID_MAIN, ERROR, tag, msg + '\n' + getStackTraceString(tr));
    }

    /**
     * Handy function to get a loggable stack trace from a Throwable
     * @param tr An exception to log
     */
    public static String getStackTraceString(Throwable tr) {
        if (tr == null) {
            return "";
        }

        // This is to reduce the amount of log spew that apps do in the non-error
        // condition of the network being unavailable.
        Throwable t = tr;
        while (t != null) {
            if (t instanceof UnknownHostException) {
                return "";
            }
            t = t.getCause();
        }

        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        tr.printStackTrace(pw);
        pw.flush();
        return sw.toString();
    }

    /**
     * Low-level logging call.
     * @param priority The priority/type of this log message
     * @param tag Used to identify the source of a log message.  It usually identifies
     *        the class or activity where the log call occurs.
     * @param msg The message you would like logged.
     * @return The number of bytes written.
     */
    public static int println(int priority, String tag, String msg) {
        return println(LOG_ID_MAIN, priority, tag, msg);
    }

    /** @hide */ public static final int LOG_ID_MAIN = 0;
    /** @hide */ public static final int LOG_ID_RADIO = 1;
    /** @hide */ public static final int LOG_ID_EVENTS = 2;
    /** @hide */ public static final int LOG_ID_SYSTEM = 3;
    /** @hide */ public static final int LOG_ID_CRASH = 4;

    /** @hide */ @SuppressWarnings("unused")
    public static int println(int bufID,
            int priority, String tag, String msg) {
        return 0;
    }
}

 

각 Log Level 이 존재하고 앞 글자를 따서 메서드 이름으로 사용하고 있다.

공통적으로 String tag를 파라미터로 받는데 이 부분이 로그 찍을 때 어디서 로그를 찍었는데 나타내는 용도로 이용된다.

보통 많은 사람들이 Class를 만들고 첫 줄에 다음과 같은 코드를 작성할 것이다.

나 역시도 그랬고... 그러나 Rename 등의 Refactoring 과정을 거친다면 하드코딩된 부분은 매뉴얼로 수정할 수밖에 없다. 

그러나 다음과 같은 방법으로 이용할 수 있다. 

public class LoginActivity extends AppCompatActivity {

    private final String TAG = this.getClass().getSimpleName().trim().substring(0, 22);
    
    ....
}    

 

해당 getClass(). getName() 은 패키지 경로까지 다 나타내므로 getSimpleName()을 이용하고 trim()으로 공백도 제거해준다. 그리고 가장 중요한 것은... Log의 String tag length는 23 이하여야 한다.

그래서 substring으로 22까지 줬다. 이게 바로 간편하고 심플한 방법이다. 

그러나.. 당최 왜 23 이하로 써야 하는지 모르겠다..

따라서 다시 구글링 ㄱㄱ 그리고 한 답변을 발견했다.

 

Below API 26 (Oreo) the limit of system property keys was 31 characters. And "log.tag.".length() + 23 equals 31. If you call Log.isLoggable below Android Oreo with a tag longer than 23 characters it will throw, as described in the source code. Since Android O this limit no longer applies.

결국 오레오 이하의 버전을 위한 조치였군.. 호환성을 생각해야 하는 안드로이 드니까.. 오레오가 deprecated 될 정도로 오랜 시간이 지나면 안 써도 되겠군..

 

<참고자료>

developer.android.com/reference/android/util/Log

 

Log  |  Android 개발자  |  Android Developers

 

developer.android.com

stackoverflow.com/questions/28168622/the-logging-tag-can-be-at-most-23-characters/28168739

 

The logging tag can be at most 23 characters

Since update AS 1.1 Preview 2, I'm getting red lines under all my Log messages Log.d(TAG, "message"); With message: "The logging tag can be at most 23 characters..". I didn't update anything

stackoverflow.com

 

+ Recent posts