Answer the question
In order to leave comments, you need to log in
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);
private final Logger log = LoggerFactory.getLogger(this.getClass());
Answer the question
In order to leave comments, you need to log in
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());
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);
It’s good to pull this through DI, and make the declaration in this style:
@InjectLogger
private Logger logger;
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…
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?
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 questionAsk a Question
731 491 924 answers to any question