R
R
relgames2012-03-05 18:28:53
Java
relgames, 2012-03-05 18:28:53

Java logging: how do you declare a log field in a class

There are 2 main ways to declare a log field in your class:

private static final Logger log = LoggerFactory.getLogger(ClassName.class);

or
private final Logger log = LoggerFactory.getLogger(this.getClass());

I usually use the second method - fewer refactoring errors (for example, the classes were renamed, but the log field was forgotten). But then I thought - maybe there are some drawbacks of this approach that I don’t see?

What approach are you using?

Answer the question

In order to leave comments, you need to log in

7 answer(s)
S
SergeyGrigorev, 2012-03-05
@relgames

I use the first method, I made a macro specifically for this in Intellij IDEA. Especially so that even if the class is later inherited by someone, the log is still tied to a specific class and it is easier to find the line where the message was generated.
private static final org.slf4j.Logger LOGGER =
org.slf4j.LoggerFactory.getLogger($CLASS_NAME$.class.getName());

L
Lendon, 2012-03-05
@Lendon

Logger is declared for the class, so you need to use the class level modifier - static. Those. I think the first option is better.
To declare a logger, I use a template in eclipse:

${:import(org.slf4j.Logger, org.slf4j.LoggerFactory)}
private static final Logger log = LoggerFactory.getLogger(${primary_type_name}.class);

M
MikeMirzayanov, 2012-03-06
@MikeMirzayanov

It’s good to pull this through DI, and make the declaration in this style:

@InjectLogger
private Logger logger;

R
relgames, 2012-03-06
@relgames

slf4j.org/faq.html#declared_static

B
barker, 2012-03-06
@barker

Of course, the first way. And when refactoring, what IDE is this in which it will not be renamed and in the declaration the name? And how can you forget it, especially if it stops compiling? I do not understand…

P
png, 2012-03-05
@png

Definitely the first for most cases.
if you refactor using the same idea, which can replace the class name in all places where it is used. Replaces even in comments and non-java files.
The second approach is not correct if you do not understand the difference. Since resources (both memory and processor) are not rationally used, consider that you create its own Logger object for each object. It will be created when the object is created, destroyed when the main object is destroyed.
Do you need it?

M
mark_stein, 2012-03-06
@mark_stein

I also use the first option, but I still suffer - to write the variable name in small letters 'log' or large 'LOG' - according to the rules, constants must be large, but I don’t want to.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question