学习springBoot(4)log4j2日志框架整合

1,813 阅读2分钟

因为需要,所以在这补充一下springboot 的日志配置,这里使用了log4j2作为日志框架, 其它的也有很多 ,Logback,Log4j 等。。。

首先排除spring boot中的logback的依赖包

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
			<exclusions>
			    <!--排除这个默认的日志组件,一定要有!!!-->
				<exclusion>
					<groupId>org.springframework.boot</groupId>
					<artifactId>spring-boot-starter-logging</artifactId>
				</exclusion>
			</exclusions>
		</dependency>

然后添加log4j2的依赖包:

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-log4j2</artifactId>
		</dependency>
		
		 <!-- 加上这个才能辨认到log4j2.yml文件 -->
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-yaml</artifactId>
        </dependency>

加入log4j2的配置文件,resources下添加log4j2.xml或者log4j2-spring.xml,启动后spring boot自动加载,不需要在application.yml 中在指定配置文件。

开始使用了xml格式的配置文件,后来突发奇想都换成了yml文件。。。。两个都贴出来吧

log4j2.xml:这个配置的比较简单

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <properties>
        <!-- 文件输出格式 -->
        <property name="PATTERN">%d{yyyy-MM-dd HH:mm:ss.SSS} |-%-5level [%thread] %c [%L] -| %msg%n</property>
    </properties>

    <appenders>
        <Console name="CONSOLE" target="system_out">
            <PatternLayout pattern="${PATTERN}" />
        </Console>
    </appenders>

    <loggers>
        <logger name="com.roncoo.education" level="debug" />
        <root level="info">
            <appenderref ref="CONSOLE" />
        </root>
    </loggers>

</configuration>

log4j2.yml:

Configuration:
  status: warn

  Properties: # 定义全局变量
    Property: # 缺省配置(用于开发环境)。其他环境需要在VM参数中指定,如下:
      #测试:-Dlog.level.console=warn -Dlog.level.xjj=trace
      #生产:-Dlog.level.console=warn -Dlog.level.xjj=info
      - name: log.level.console
        value: debug
      - name: log.level.xjj
        value: info
      - name: log.path
        value: D:/log
      - name: project.name
        value: springboot1

  Appenders:
    Console:  #输出到控制台
      name: CONSOLE
      target: SYSTEM_OUT
      ThresholdFilter:
        level: ${sys:log.level.console} # “sys:”表示:如果VM参数中没指定这个变量值,则使用本文件中定义的缺省全局变量值
        onMatch: ACCEPT
        onMismatch: DENY
      PatternLayout:
        pattern: "%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n"
    RollingFile: # 输出到文件,超过100MB归档
      - name: ROLLING_FILE
        ignoreExceptions: false
        fileName: ${log.path}/${project.name}.log
        filePattern: "${log.path}/$${date:yyyy-MM}/${project.name}-%d{yyyy-MM-dd}-%i.log.gz"
        PatternLayout:
          pattern: "%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n"
        Policies:
          SizeBasedTriggeringPolicy:
            size: "100 MB"
        DefaultRolloverStrategy:
          max: 1000

  Loggers:
    Root:
      level: info
      AppenderRef:
        - ref: CONSOLE
        - ref: ROLLING_FILE
    Logger: # 为org.springframework包配置特殊的Log级别,方便调试
      - name: org.springframework
        additivity: false
        level: ${sys:log.level.xjj}
        AppenderRef:
          - ref: CONSOLE
          - ref: ROLLING_FILE

Configuration上有个INFO,Root下有个debug,需要明确的是Configuration的status是log4j2本身的日志打印级别,并是不全局日志级别。而Root下的leve,则恰恰是全局日志级别。

Appenders下面定义日志输出的地方。从上面配置看,是输出到了控制台。

这样,log4j2就配置成功了,重启下项目看下效果

 private static Logger logger = LoggerFactory.getLogger(Springboot1Application.class);
    public static void main(String[] args) {
        SpringApplication.run(Springboot1Application.class, args);
        logger.info("项目启动成功!~~~~~~~~~~~~~~~~~");
    }

启动日志也没有问题,D:\log 目录下也生成了springboot1.log 日志文件。

2018-08-22 12:01:59.865 INFO  org.apache.juli.logging.DirectJDKLog 180 log - Starting ProtocolHandler ["http-nio-8082"]
2018-08-22 12:01:59.880 INFO  org.apache.juli.logging.DirectJDKLog 180 log - Using a shared selector for servlet write/read
2018-08-22 12:01:59.900 INFO  org.springframework.boot.web.embedded.tomcat.TomcatWebServer 206 start - Tomcat started on port(s): 8082 (http) with context path ''
2018-08-22 12:01:59.906 INFO  org.springframework.boot.StartupInfoLogger 59 logStarted - Started Springboot1Application in 15.4 seconds (JVM running for 17.972)
2018-08-22 12:01:59.911 INFO  com.Springboot1Application 18 main - 项目启动成功!~~~~~~~~~~~~~~~~~

上面。。。。只是简单的配置了下,后面在深入研究下详细配置。