Andrew
Andrew

Reputation: 49606

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)

Upvotes: 5

Views: 15623

Answers (3)

baumato
baumato

Reputation: 378

This solution:

private static final Logger logger = LoggerFactory.getLogger(SignUpController.class);

has the slight disadvantage that it gets copied and pasted into other classes and it is easy to forget to adjust the class name. Thus I prefer this solution which is safe for "copy & paste":

private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());

Upvotes: 3

rajuGT
rajuGT

Reputation: 6404

Use the first one

private static final Logger logger = LoggerFactory.getLogger(SignUpController.class);

Because, that api (which is accepting class object), the method internally calls fully qualified class name, so the logging control/configuration can be done properly.

I prefer private static final because

private: for the logger instance should not be available to outside the class

static: there is no use of having separate instance for each object of a class

final to not to change the reference once it has been initialized.

Upvotes: 9

hotzst
hotzst

Reputation: 7496

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.

Upvotes: 7

Related Questions