背景
- 公司使用maven、Spring Boot搭建微服务项目,使用log4j输出日志
- Maven 3.5
- SPring Boot 2.2
项目配置
- 项目目录如下
- pom.xml配置(只显示和log4j有关的配置)
-
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>${spring-boot-starter.version}</version> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>io.github.lognet</groupId> <artifactId>grpc-spring-boot-starter</artifactId> <version>3.5.1</version> <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-log4j</artifactId> <version>1.3.8.RELEASE</version> </dependency>
-
- log4j.properties
-
log4j.rootLogger=INFO,DEBUG,ERROR, stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{yy/MM/dd HH:mm:ss} %p %c{2}: %m%n
#----------------------------文件存在项目根目录下-----------------------# #---------------------------------------------------------------------------------------------------- #输出INFO级别以上的内容到info.log中 log4j.logger.INFO=INFO log4j.appender.INFO = org.apache.log4j.DailyRollingFileAppender log4j.appender.INFO.File = logs/supersiver/objects/info.log log4j.appender.INFO.Threshold = INFO log4j.appender.INFO.Append = true log4j.appender.INFO.layout = org.apache.log4j.PatternLayout log4j.appender.INFO.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n #----------------------------------------------------------------------------------------------------- #输出DEBUG 级别以上的日志到debugger.log log4j.logger.DEBUG=DEBUG log4j.appender.DEBUG = org.apache.log4j.DailyRollingFileAppender log4j.appender.DEBUG.File = logs/supersiver/objects/debugger.log log4j.appender.DEBUG.Threshold = DEBUG log4j.appender.DEBUG.Append = true log4j.appender.DEBUG.layout = org.apache.log4j.PatternLayout log4j.appender.DEBUG.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n #----------------------------------------------------------------------------------------------------- #输出ERROR 级别以上的日志到error.log log4j.logger.ERROR=ERROR log4j.appender.ERROR = org.apache.log4j.DailyRollingFileAppender log4j.appender.ERROR.File =logs/supersiver/objects/error.log log4j.appender.ERROR.Threshold = ERROR log4j.appender.ERROR.Append = true log4j.appender.ERROR.layout = org.apache.log4j.PatternLayout log4j.appender.ERROR.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
-
拓展
- Spring Boot本身就内置了日志功能,使用的是LogBack,所以我们想要使用log4j作为日志输出的话,需要在pom.xml中将Spring Boot内置的日志LogBack排除,否则很容易和log4j产生冲入,导致项目报错