SpringBoot integrated Log4j

(1) Add dependency in pom.xml

        <!--Remove springboot Default log-->

        <!--log4j Dependence-->

Spring boot uses its own log by default. You need to remove its own spring boot starter logging before the log4j we introduced will work.



(2) Create log4j.properties under resources

# Global logging configuration
log4j.rootLogger=DEBUG, stdout,D

# MyBatis logging configuration...

# Console output...
log4j.appender.stdout.Threshold = DEBUG
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

# File output...
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
#Relative path, relative to the root of tomcat.
#log4j.appender.D.File = ../logs/error.log
log4j.appender.D.File = D:/logs/error.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = ERROR
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

Spring boot officially recommends that the file name of the log configuration end with - spring, log4j-spring.properties. Of course, using log4j.properties is fine.


Now that log4j has been integrated, springboot will automatically use log4j to manage logs.




We can manually output logs:

        Logger logger = Logger.getLogger(UserController.class);  //Class object passed in the current class
        logger.debug("This is debug message.");
        logger.error("This is error message.");

Logger is generally written in the form of member variable, which is convenient for use in all methods of this class:

private Logger logger = Logger.getLogger(UserController.class);


Note that the imported Logger is:

import org.apache.log4j.Logger;

Don't misdirect.

Tags: Java log4j Spring Apache SpringBoot

Posted on Sun, 09 Feb 2020 07:07:54 -0800 by Arc