Adding Log4j2
All the Spring Boot starters depend on spring-boot-starter-logging, which uses Logback by default. For using Log4j2, you need to exclude spring-boot-starter-logging and add spring-boot-starter-log4j2 dependency.
如果引用的log4j2没有起作用,因为pom文件中没有正确的排除掉Logback,请检查pom文件。
Open pom.xml file and add the following snippet to the “dependencies” section
<!-- Exclude Spring Boot's Default Logging -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- Add Log4j2 Dependency -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
Spring Boot automatically configures Log4j if it finds a file named log4j2.xml or log4j2.json or log4j2.yaml in the classpath.
In this article, we’ll configure log4j 2 using XML. Create a new file log4j2.xml inside src/main/resources directory, and add the following configuration to it -
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" monitorInterval="30">
<Properties>
<Property name="LOG_PATTERN">
%d{yyyy-MM-dd HH:mm:ss.SSS} %5p ${hostName} --- [%15.15t] %-40.40c{1.} : %m%n%ex
</Property>
</Properties>
<Appenders>
<Console name="ConsoleAppender" target="SYSTEM_OUT" follow="true">
<PatternLayout pattern="${LOG_PATTERN}"/>
</Console>
</Appenders>
<Loggers>
<Logger name="com.example.log4j2demo" level="debug" additivity="false">
<AppenderRef ref="ConsoleAppender" />
</Logger>
<Root level="info">
<AppenderRef ref="ConsoleAppender" />
</Root>
</Loggers>
</Configuration>
The above configuration defines a simple ConsoleAppender and declares two loggers - an application specific logger and the the root logger.
Let’s add some logging code to check our logger configuration. Open Log4j2DemoApplication.java and replace it with the following code -
package com.example.log4j2demo;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Log4j2DemoApplication implements ApplicationRunner {
private static final Logger logger = LogManager.getLogger(Log4j2DemoApplication.class);
public static void main(String[] args) {
SpringApplication.run(Log4j2DemoApplication.class, args);
}
@Override
public void run(ApplicationArguments applicationArguments) throws Exception {
logger.debug("Debugging log");
logger.info("Info log");
logger.warn("Hey, This is a warning!");
logger.error("Oops! We have an Error. OK");
logger.fatal("Damn! Fatal error. Please fix me.");
}
}
We have added 5 simple logs of different log levels. When you run the app, it logs everything on the console.
If you want your logs to be written to a file, then you can use a RollingFile appender. RollingFile appender creates a new file whenever the log file reaches a certain threshold specified by the triggering policy.
It stores the old log files with names matching the pattern specified by the filePattern parameter -
<!-- Rolling File Appender -->
<RollingFile name="FileAppender" fileName="logs/log4j2-demo.log"
filePattern="logs/log4j2-demo-%d{yyyy-MM-dd}-%i.log">
<PatternLayout>
<Pattern>${LOG_PATTERN}</Pattern>
</PatternLayout>
<Policies>
<SizeBasedTriggeringPolicy size="10MB" />
</Policies>
<DefaultRolloverStrategy max="10"/>
</RollingFile>
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
<Appenders>
<Console name="SYSOUT" target="SYSTEM_OUT">
<PatternLayout patter="%d [%t] %-5p [%c] - %m%n "/>
</Console>
<!-- name可以自定义,作用是在Loggers中AppenderRef中使用 -->
<!-- fileName定义输出文件名称(当前文件) -->
<!-- filePattern定义输出文件名称(文件满足条件后自动截断,生成历史文件) -->
<RollingFile name="DEBUG_ROLLING_FILE"
fileName="~/logs/xxx/logs.logs"
filePattern="~/logs/xxx/logs/%d{yyyy-MM-dd}-debugs.log">
<PatternLayout>
<Pattern>%d [%t] %-5p [%c] - %m%n </Pattern>
</PatternLayout>
<!-- 文件截断的条件,具体参考文档 -->
<Policies>
<TimeBasedTriggeringPolicy interval="24"/>
<SizeBasedTriggeringPolicy size="250 MB"/>
</Policies>
</RollingFile>
<!-- 同一来源的Appender可以定义多个 -->
<RollingFile name="ERROR_ROLLING_FILE"
fileName="~/logs/xxx/logs/error-logs.logs"
filePattern="~/logs/xxx/logs/%d{yyyy-MM-dd}-error.log">
<!-- 可以通过该参数来设置获取日志的权限 -->
<ThresholdFilter level="error" onMatch="ACCEPT" onMismatch="DENY"/>
<PatternLayout>
<Pattern>%d [%t] %-5p [%c] - %m%n </Pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy interval="24"/>
<SizeBasedTriggeringPolicy size="250 MB"/>
</Policies>
</RollingFile>
</Appenders>
<Loggers>
<Root level="debug">
<AppenderRef ref="SYSOUT"/>
<AppenderRef ref="DEBUG_ROLLING_FILE"/>
<AppenderRef ref="ERROR_ROLLING_FILE"/>
</Root>
<logger name="org.apache.http" level="ERROR" />
<!-- Spring -->
<logger name="org.springframework" level="ERROR" />
<!-- mybatis loggers -->
<logger name="com.ibatis" level="INFO" />
<logger name="com.ibatis.common.jdbc.SimpleDataSource" level="DEBUG" />
<logger name="com.ibatis.common.jdbc.ScriptRunner" level="DEBUG" />
<logger name="com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate" level="DEBUG" />
<!-- sql loggers -->
<logger name="java.sql.Connection" level="DEBUG" additivity="true"/>
<logger name="java.sql.Statement" level="DEBUG" additivity="true" />
<logger name="java.sql.PreparedStatement" level="=debug,stdout" additivity="true"/>
<logger name="java.sql.ResultSet" level="DEBUG" additivity="true"/>
</Loggers>
</Configuration>
更多详细操作见下面链接
https://www.callicoder.com/spring-boot-log4j-2-example/