How do You log using log4j in Spring Boot

  • 2020-06-03 06:29:57
  • OfStack


Spring Boot USES Commons Logging for all internal logs, but the default configuration also provides support for common logs such as Java Util Logging, Log4J, Log4J2 and Logback. Each Logger can be configured to output log content using the console or file. This paper mainly introduces how to use log4j in Spring Boot to record the log.

Introduce log4j dependencies

When creating the Spring Boot project, we introduced ES28en-ES29en-ES30en, which contains ES31en-ES32en-ES33en-ES34en. The dependent content is
Spring Boot is the default logging framework, Logback, so before we introduce log4j, we need to exclude the dependencies of this package and then introduce log4j dependencies, as follows:


Configuration log4j properties

After the introduction of the log4j dependency, you only need to add the configuration file in the src/main/resources directory to start configuring the application logs.

Console output

Set the output level of the root log to INFO and appender to stdout for the console with the following configuration

# LOG4J configuration 
log4j.rootCategory=INFO, stdout
#  Console output 
 log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %5p %c{1}:%L - %m%n

Output to file

In the development environment, we just output it to the console, but in the production or test environment, perhaps persisting the log content so that we can trace the cause of the problem.
You can add appender to different files on a daily basis by adding the following appender content. You also need to add appender named file for ES74en4j.rootCategory.
This allows the root log to be printed to the logs/ all.log file.

log4j.rootCategory=INFO, stdout, file
# root Log output 
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %5p %c{1}:%L - %m%n

Classification of output

1. Different package can be used for output. By defining the appender output to logs/ my.log and setting the log level under the com.didispace package
For DEBUG level, appender is set to output to logs/ my.log named didifile.

# com.juzi Log configuration under the package, didifile
# com.didispace Log output below 
log4j.appender.didifile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %5p %c{1}:%L ---- %m%n

Different levels can be categorized, such as output to a specific log file for the ERROR level, as configured below.

# error Log output 
log4j.appender.errorfile.Threshold = ERROR 
log4j.appender.errorfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %5p %c{1}:%L - %m%n


The above is the whole content of this article, I hope the content of this article can bring 1 definite help to your study or work, if you have any questions, you can leave a message to communicate.

Related articles: