Recently I had the “pleasure” to add logging to a Java application. It was the most difficult thing to do in the whole program. There is so much documentation available and no two web pages are alike. Which is correct and which is not?
SLF4J provides a facade and common API that can used to log to popular backends such as Log4J, Logback, java.util.logging etc. java.util.logging comes in-built with Java but is not recommended. Using SLF4J is recommended because then you can easily swap out the actual implementation without making a change to a single line of code. Log4J is the most popular logging library used in Java so we’ll use that in this article.
There are two difficulties I encountered in attempt to add logging:
- what is the exact set of dependencies to be added in
pom.xml? - how to add the config file? what should it look like? what should it contain? where should it be stored? this part is most difficult
To begin add following to your Maven dependencies:
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.36</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-slf4j-impl -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.18.0</version>
</dependency>
<!-- https://github.com/eugenp/tutorials/blob/master/logging-modules/log4j/pom.xml -->
<!--log4j2 dependencies -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.18.0</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.18.0</version>
</dependency>
<!--disruptor for log4j2 async logging -->
<!-- this is required by log4j-core to perform async logging. see https://logging.apache.org/log4j/2.x/runtime-dependencies.html -->
<dependency>
<groupId>com.lmax</groupId>
<artifactId>disruptor</artifactId>
<version>${disruptor.version}</version>
</dependency>
The hardest part was adding the configuration file. When using v2 of log4j this config file is now named log4j2.properties and should be saved under src/main/resources. See this and this to understand its format and content.
I can’t believe it. Tried it today and still doesn’t work. If you don’t care about logging to a file just add following:
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>2.0.16</version>
</dependency>
Further Reading
Performance comparison of various logging frameworks (mainly log4j vs. java.util.logging) (source):
