Log4J: Strategies for creating Logger instances

Viewed 62552

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

10 Answers

the best and easiest method to create custom loggers, notlinked to any classname is:

// create logger
Logger customLogger = Logger.getLogger("myCustomLogName");

// create log file, where messages will be sent, 
// you can also use console appender
FileAppender fileAppender = new FileAppender(new PatternLayout(), 
                                             "/home/user/some.log");

// sometimes you can call this if you reuse this logger 
// to avoid useless traces
customLogger.removeAllAppenders();

// tell to logger where to write
customLogger.addAppender(fileAppender);

 // send message (of type :: info, you can use also error, warn, etc)
customLogger.info("Hello! message from custom logger");

now, if you need another logger in same class, no problem :) just create new one

// create logger
Logger otherCustomLogger = Logger.getLogger("myOtherCustomLogName");

now see the code above and create new fileappender so your output will be sent in other file

This is usefull for (at least) 2 situations

  • when you want separate error from info and warns

  • when you manage multiple processes and you need output from each process

ps. have questions ? feel free to ask! :)

Related