首先自定义一个log4j2.xml文件:
- <?xml version="1.0" encoding="UTF-8"?>
- <Configuration status="WARN">
- <Appenders>
- <Console name="Console" target="SYSTEM_OUT" follow="true">
- <PatternLayout>
- <pattern>%d %p %C{1.} [%t] %m%n</pattern>
- </PatternLayout>
- </Console>
- <!-- 按日期每天生成log文件 -->
- <RollingFile name="RollingFile" fileName="temp/CL_BATCH.log"
- filePattern="temp/CL_BATCH-%d{yyyy-MM-dd}.log">
- <PatternLayout pattern="%d %p %C{1.} [%t] %m%n"/>
- <Policies>
- <TimeBasedTriggeringPolicy interval="1"/>
- </Policies>
- <!-- log文件只打印error级别信息 -->
- <Filters>
- <ThresholdFilter level="error" onMatch="ACCEPT" onMismatch="DENY"/>
- </Filters>
- </RollingFile>
- </Appenders>
- <Loggers>
- <!-- 输出info级别信息 -->
- <Root level="info">
- <AppenderRef ref="Console" />
- <AppenderRef ref="RollingFile" />
- </Root>
- </Loggers>
- </Configuration>
接下来在pom.xml按照spring boot的文档进行定义
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
- <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>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-log4j2</artifactId>
- </dependency>
最后在application.properties文件中,指定加载的log文件位置:
- logging.config=classpath:log4j2.xml
这样,我们便能在程序中使用log了,目前我们的日志是在控制台进行输出,如果需要输出到文件中的话,添加<AppenderRef ref="File" />即可