Standard way to implement Logger for different classes in Java?

I am building a Javafx application with many classes. I would like to use java log from all classes. But all options seem to have redundant or duplicate code. These are the ones I can think of:

  • declare the registrar as a private static final field in each class ie

    private static final Logger LOGGER = Logger.getLogger (MyClass.class.getName ());

This parameter seems annoying to do this in every class.

  1. pass Logger from the main class to each constructor

Again doesn't seem elegant

  1. create a class for the registrar only, and then call the static methods for this class for each log item. It seems that creating an extra class just for the registrar is excessive.

So how do you guys handle this situation? Is it just a matter of choosing the least bad option?

+4
java logging
source share
2 answers

I do not agree with the β€œredundancy” of the third option: the β€œwrapper” option is actually quite elegant, because it has a dedicated journal class ( SRP ), and it allows you to switch implementations ( log4j , apache-commons-logging , java. util.logging , etc.) "under the hood" without linking the rest of the code with this implementation.

As Luiggy mentioned in the comments below, SLF4J is such an implementation.

0
source share

Option 1, associated with option 3 (for example, people mentioned using a wrapper such as slf4j), which will allow widespread use of switching between implementations.

declare Logger as a private static final field in each class ie private static final Logger LOGGER = Logger.getLogger(MyClass.class.getName()); 

Declaring a registrar is not such a big deal, and you should be able to define a new class template in your development environment that automatically generates a registrar code.

+1
source share

All Articles