Thursday
Mar072013

Java: Copy/Paste-Safe Logger Creation

We've all copied and pasted a Logger from one class to the other, forgetting to change the class name.

// WRONG
public class SomeNewClass
{
    // OOPS! I forgot to change the class name!
    private final Logger _logger = LoggerFactory.getLogger(SomeOtherClass.class);

    // …  
}

Here, use this smarter LoggerFactory which uses the stack trace to figure out what class you really mean. This is safe from copypasta laziness.

package org.blakecaldwell.logging;

import org.slf4j.Logger;

/**
 * Smart logger that uses reflection to figure out the logged class
 */
public final class ClassLoggerFactory
{
    /**
     * Disallow factory instances.
     */
    private ClassLoggerFactory()
    {
    }

    /**
     * Use the stack trace to determine the appropriate logger.
     * 
     * @return a logger for the direct caller's class.
     */
    public static Logger make()
    {
        Throwable t = new Throwable();
        StackTraceElement directCaller = t.getStackTrace()[1];
        return org.slf4j.LoggerFactory.getLogger(directCaller.getClassName());
    }
}

Then, to use this logger:

// CORRECT
public class SomeNewClass
{
    // No chance for screwing up anymore!
    private final Logger _logger = ClassLoggerFactory.make();

    // …  
}

PrintView Printer Friendly Version

EmailEmail Article to Friend

Reader Comments

There are no comments for this journal entry. To create a new comment, use the form below.

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>
« PDF Emailer v2.1: Multiple recipient support | Main | Java: Embedding Spring Batch Admin Into An Existing Application »