HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

TaggedLogger - Log wrapper

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
wrappertaggedloggerlog

Problem

I wrote this class in order to not having to write tag every time (because of code duplication and risk of typos).

public class TaggedLogger {

    public static final TaggedLogger GLOBAL = new TaggedLogger("Global");

    private final String tag;

    public static TaggedLogger forClass(Class someClass) {
        return new TaggedLogger(someClass.getName());
    }

    public TaggedLogger(String tag) {
        this.tag = tag;
    }

    public void debug(String message) {
        Log.d(tag, message);
    }

    public void info(String message) {
        Log.i(tag, message);
    }

    public void exception(String message) {
        Log.e(tag, message);
    }

    public void exception(String message, Throwable exception) {
        Log.e(tag, message, exception);
    }

    // skipped

}


Using:

public class MainActivity extends Activity {
    private static final TaggedLogger LOGGER = TaggedLogger.forClass(MainActivity.class);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        LOGGER.debug("Initialization: start");
        init(savedInstanceState);
    }

    // skipped

}


What do you think? Maybe this class is useless?

Help me choose a more appropriate name for this class (if TaggedLogger isn't good) ?

Solution

I do not consider your class useless, I have actually done a similar thing myself. Very similar actually. Perhaps even exactly the same, pretty much.

Overall, your code is very well-written. You use final and private where you can, which I like.

A few comments:

private static final TaggedLogger LOGGER = TaggedLogger.forClass(MainActivity.class);


Even though it is correct that constants are written in ALL_CAPS. One exception for this is loggers. If you write LOGGER.info and stuff often, that LOGGER will pick on your eyes after a while. I would recommend using the name logger (lowercase) instead.

public static final TaggedLogger GLOBAL = new TaggedLogger("Global");


I am not sure if you really need this one. Especially not inside that class.

It is good that you have not made your class a singleton at least, but I'm not sure if this public static 'global' is really necessary.

I can recommend using log4j for Android for logging. Log4j is a very nice and popular logging framework for Java, and it is possible to get it working on Android.

Code Snippets

private static final TaggedLogger LOGGER = TaggedLogger.forClass(MainActivity.class);
public static final TaggedLogger GLOBAL = new TaggedLogger("Global");

Context

StackExchange Code Review Q#61682, answer score: 2

Revisions (0)

No revisions yet.