Spring Cloud Spring Boot mybatis Distributed Microservice Cloud Architecture (38) Logs using log4j

Introducing log4j dependencies

When we created the Spring Book project, we introduced spring-boot-starter, which includes spring-boot-starter-logging, which is the default log framework of Spring Boot, Logback. So before we introduce log4j, we need to eliminate the dependency of the package and then introduce log4j dependency, as follows:



Configure log4j.properties

After introducing log4j dependencies, you can configure the application logs by simply adding the log4j.properties configuration file to the src/main/resources directory.

console output

Set the output level of the root log to INFO and appender to output 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 a file

In the development environment, we just export it to the console, but in the production or test environment, maybe the log content is persisted to facilitate traceability of the cause of the problem. By adding the following appender content, you can output it to different files by day. At the same time, you need to add an appender named file for log4j.rootCategory, so that the root log can be exported 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

Classified output

When we have more logs, it is very difficult to find problems. The common method is to classify logs, such as:

  • It can be output according to different packages. By defining the appender output to logs/my.log, and setting the log level under the com.didispace package to DEBUG level, appender to appender output to logs/my.log named didifile.
    # Log configuration under com.didispace package
    log4j.category.com.didispace=DEBUG, didifile
    # Log Output under com.didispace
    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 ERROR level output to a specific log file, the specific configuration can be as follows.
    # 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

    This article mainly introduces how to introduce log4j into spring boot and some basic usage.

  • Source of source code

Tags: log4j Spring Apache

Posted on Thu, 20 Dec 2018 04:15:05 -0800 by edmore