Last Updated on 02 August 2020   |   Print Email
This tutorial guides you how to use Log4j2 – a popular Java logging framework – in a Spring Boot project.
1. Why Log4j2?
Log4j2 is a successor to Log4j 1.x. Log4j2 provides significant improvements over Log4j 1.x and it also fixes some issues in Logback – also a successor to Log4j 1.x. Log4j2 uses the next-generation asynchronous loggers so it’s faster and better than Log4j 1.x and Logback.For details about Log4j2, visit its homepage here.
2. Configure Maven Dependencies for using Log4j2 in Spring Boot
Spring Boot uses Logback as the default logging framework implementation, so to use Log4j2 you need to do some extra configuration in the Maven project file.First, you need to exclude spring-boot-starter-logging dependency:
Then you will see Spring Boot removes the jar files of Logback and adds jar files: log4j-core, log4j-slf4j (for bridge between Log4j and SLF4J), log4j-jul (for bridge between Log4j and Java Util Logging), and jul-to-slf4j (for bridge between Java Util Logging and SLF4J).
That means if the project is using SLF4J API, then you don’t have to change the existing logging code. And you see Java Util Logging because it is used for internal APIs of Spring Boot.
3. Configure Logging to Console (Console Appender)
Next, you need to create log4j2.xml or log4j2-spring.xml file under the src/main/resources directory in order to use Log4j2 for your Spring Boot project.Below is the XML code for the simplest Log4j2 configuration: output log messages to the console.
Let me explain the pattern layout for each line of log written to the console: %d for date and time, %t for thread name, %level for log level, %c for logger name (usually package name and class name), %msg for log message, and %n for a line separator.You can use the following pattern for more readable log messages:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.
Hey this was really helpful. However i noticed 1 issue here. We i embedded this in my project having java 11, i found excluding with spring-boot-starter could not run the application. It resulted in ClassCastException: org.apache.logging.log4j.simple.SimpleLoggerContext cannot be cast to org.apache.logging.log4j.core.LoggerContext. So i excluded in spring-boot-starter-web artifact .
Comments
The file was not generated for me, still looking for the solution.