Search code examples
javalogginglog4jlogback

What's the best way to initialise a logger in a class?


I've got two options to initialise a Logger within a class.

The first way is providing an instance of the Class<?>:

logger = LoggerFactory.getLogger(SignUpController.class);

and the second one is passing a String identifier (the package and the class name):

logger = LoggerFactory.getLogger("controller.SignUpController");

The questions are:

What's the best way to initialise a logger for a class?
What modifiers should be used with? (access modifiers, static, final)


Solution

  • I use

    public final Logger = LogFactory.getLogger(getClass());
    

    For one this will ensure always the correct class name even after a refactoring of the class name. The overhead of one logger instance per instantiated object vs per class is neglectable.

    I only use a static logger when I need to log something in as static context and then initialize it with your first approach.