spring框架
首先引入依赖
<dependency><groupId>org.apache.logging.log4j</groupId><artifactId>log4j-core</artifactId><version>2.11.1</version></dependency>
其次在resources下新增log4j2.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<!--根节点 -->
<configuration><!--附加器节点--><appenders> <!--最常用的两种附加器控制台输出日志与文件输出日志--><Console name="Console" target="SYSTEM_OUT"><PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/></Console><!--最简单的文件输出日志附加器--><file name="file" fileName="log/mylog.log"><PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/></file></appenders><!--在loggers中引用附加器 --><loggers><!--根节点附加器,全局--><root level="info"> <appender-ref ref="Console"/><appender-ref ref="file"/></root></loggers>
</configuration>
测试类test.java
package Thread;import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;public class test {static Logger log = LogManager.getLogger(test.class.getName());public static void main(String[] args) {log.info("日志打印测试");log.debug("日志打印测试");}}
spring-boot框架 XML配置实现日志打印
首先还是引入依赖 ,注意一定要去掉springboot的默认日志配置
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId><exclusions><!-- 去掉springboot默认log配置 --><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-web</artifactId></dependency><dependency> <!-- 引入log4j2依赖 --><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-log4j2</artifactId></dependency>
其余的与spring的配置方式一致
spring-boot框架 yml配置实现
server:port: 8080servlet:context-path: /demo #日志打印 logging:level:Root: debugfile: log/mylog2.log