Log4J: Strategies for creating Logger instances

Adrian picture Adrian · Nov 20, 2009 · Viewed 59.6k times · Source

I decided to use Log4J logging framework for a new Java project. I am wondering what strategy should I use for creating/managing Logger instances and why?

  • one instance of Logger per class e.g.

    class Foo {
        private static final Logger log = Logger.getLogger(Foo.class);
    }
    
  • one instance of Logger per thread
  • one instance of Logger per application
  • horizontal slicing : one instance of Logger in each layer of an application (e.g. the view layer, the controller layer and the persistence layer)
  • vertical slicing : one instance of Logger within functional partitions of the application

Note: This issue is already considered to some extent in these articles:

Whats the overhead of creating a Log4j Logger

Answer

PSpeed picture PSpeed · Nov 20, 2009

Typically, you'd have loggers setup per class because that's a nice logical component. Threads are already part of the log messages (if your filter displays them) so slicing loggers that way is probably redundant.

Regarding application or layer based loggers, the problem is that you have to find a place to stick that Logger object. Not a really big deal. The bigger issue is that some classes may be used at multiple levels of from multiple applications... it could be difficult to get your logger right. Or at least tricky.

...and the last thing you want is bad assumptions in your logging setup.

If you care about applications and layers and have easy separation points, the NDC is the way to go. The code can be a little excessive sometimes but I don't know how many times I've been saved by an accurate context stack showing me that Foo.bar() was called from application X in layer Y.