Last Updated: February 25, 2016
·
6.231K
· goncalossilva

Proper LOG_TAG on Android

If you develop Android apps, you probably have tons of LOG_TAG's like:

class MySuperClass {
    static final String LOG_TAG = "MySuperClass";
    // ...
}

Because that's what you're supposed to do, and that's what you see in Android's own code.

However, if you're obsessive (like most of us), you'll struggle to keep your LOG_TAG strings consistent with your class names, which will likely change throughout the project.

There's a better way:

class MySuperClass {
    static final String LOG_TAG = MySuperClass.class.getSimpleName();
    // ...
}

Now, even when you refactor your class's name, the LOG_TAG is always consistent, and you'll sleep better.

4 Responses
Add your response

It's the same principle as with the log4J Logger in standard Java code except one problem which might still occur... developers using "MySuperClass.class.getSimpleName()" in every class ;)

over 1 year ago ·

Let's hope they get the point and don't do that :D

over 1 year ago ·

Couldn't you just be using "this."?

over 1 year ago ·

Not in a static context. To do that we'd have to remove the static modifier:

final String LOG_TAG = this.getClass().getSimpleName();
over 1 year ago ·