美文网首页
SpringBoot中log4j2的使用和配置

SpringBoot中log4j2的使用和配置

作者: SpaceCat | 来源:发表于2022-01-11 23:46 被阅读0次

    这里主要演示springboot中log4j2的使用。

    1、新建样例工程

    1.1 新建工程

    File->New->Project...选择新建Maven项目:

    image.png

    点击下一步,然后输入Maven坐标:


    image.png

    设置存放目录信息:


    image.png

    点击Finish。工程创建完毕:

    image.png

    1.2 编写简单代码

    修改pom文件配置依赖,修改后的pom.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>com.space.log4j2</groupId>
        <artifactId>trial</artifactId>
        <version>1.0-SNAPSHOT</version>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.0.4.RELEASE</version>
        </parent>
    
        <dependencies>
            <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-web</artifactId>
            </dependency>
            <!-- 引入log4j2依赖 -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-log4j2</artifactId>
            </dependency>
        </dependencies>
    
    </project>
    

    新建java类com.space.log4j2.trial.Application

    package com.space.log4j2.trial;
    
    import org.apache.logging.log4j.LogManager;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    /**
     * Created by chengxia on 2021/12/7.
     */
    @SpringBootApplication
    public class Application {
        private static final org.apache.logging.log4j.Logger log = LogManager.getLogger(Application.class);
        public static void main(String[] args) {
            //日志级别以及优先级排序: OFF > FATAL > ERROR > WARN > INFO > DEBUG > TRACE > ALL
            log.trace("This is a trace level log");
            log.debug("This is a debug level log");
            log.info("This is a info level log");
            log.warn("This is a warn level log");
            log.error("This is a error level log");
            log.fatal("This is a fatal level log");
            SpringApplication.run(Application.class, args);
        }
    }
    

    新建log4j2的日志配置文件log4j2.xml

    <?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} - [%t]%c : %m%n
            </Property>
        </Properties>
        <Appenders>
            <!-- 引用前面的日志格式,将日志输出到控制台 -->
            <Console name="ConsoleAppender" target="SYSTEM_OUT" follow="true" >
                <PatternLayout pattern="${LOG_PATTERN}"/>
            </Console>
        </Appenders>
        <Loggers>
            <!-- 设置默认的日志输出级别 -->
            <Root level="info">
                <AppenderRef ref="ConsoleAppender" />
            </Root>
        </Loggers>
    </Configuration>
    

    注意,这里的日志配置文件名log4j2.xml不能修改,修改后各种奇怪的现象。
    到这里,编码和配置就完成了,最后结构如下:

    image.png

    启动运行,日志输出如下:

    com.space.log4j2.trial.Application
    2022-01-11 23:18:01.779  INFO ChengdeMBP - [main]com.space.log4j2.trial.Application : This is a info level log
    2022-01-11 23:18:01.783  WARN ChengdeMBP - [main]com.space.log4j2.trial.Application : This is a warn level log
    2022-01-11 23:18:01.784 ERROR ChengdeMBP - [main]com.space.log4j2.trial.Application : This is a error level log
    2022-01-11 23:18:01.784 FATAL ChengdeMBP - [main]com.space.log4j2.trial.Application : This is a fatal level log
    
      .   ____          _            __ _ _
     /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
    ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
     \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
      '  |____| .__|_| |_|_| |_\__, | / / / /
     =========|_|==============|___/=/_/_/_/
     :: Spring Boot ::        (v2.0.4.RELEASE)
    
    2022-01-11 23:18:02.567  INFO ChengdeMBP - [main]com.space.log4j2.trial.Application : Starting Application on ChengdeMBP with PID 1029 (/Users/chengxia/Developer/Java/JavaWeb/trial/target/classes started by chengxia in /Users/chengxia/Developer/Java/JavaWeb/trial)
    2022-01-11 23:18:02.569  INFO ChengdeMBP - [main]com.space.log4j2.trial.Application : No active profile set, falling back to default profiles: default
    2022-01-11 23:18:02.802  INFO ChengdeMBP - [main]org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@710f4dc7: startup date [Tue Jan 11 23:18:02 CST 2022]; root of context hierarchy
    2022-01-11 23:18:05.047  INFO ChengdeMBP - [main]org.springframework.boot.web.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
    2022-01-11 23:18:05.085  INFO ChengdeMBP - [main]org.apache.coyote.http11.Http11NioProtocol : Initializing ProtocolHandler ["http-nio-8080"]
    2022-01-11 23:18:05.102  INFO ChengdeMBP - [main]org.apache.catalina.core.StandardService : Starting service [Tomcat]
    2022-01-11 23:18:05.106  INFO ChengdeMBP - [main]org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.32
    2022-01-11 23:18:05.145  INFO ChengdeMBP - [localhost-startStop-1]org.apache.catalina.core.AprLifecycleListener : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [/Users/chengxia/Library/Java/Extensions:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java:.]
    2022-01-11 23:18:05.368  INFO ChengdeMBP - [localhost-startStop-1]org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
    2022-01-11 23:18:05.368  INFO ChengdeMBP - [localhost-startStop-1]org.springframework.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2578 ms
    2022-01-11 23:18:05.464  INFO ChengdeMBP - [localhost-startStop-1]org.springframework.boot.web.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/]
    2022-01-11 23:18:05.470  INFO ChengdeMBP - [localhost-startStop-1]org.springframework.boot.web.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
    2022-01-11 23:18:05.470  INFO ChengdeMBP - [localhost-startStop-1]org.springframework.boot.web.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
    2022-01-11 23:18:05.471  INFO ChengdeMBP - [localhost-startStop-1]org.springframework.boot.web.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
    2022-01-11 23:18:05.471  INFO ChengdeMBP - [localhost-startStop-1]org.springframework.boot.web.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
    2022-01-11 23:18:05.696  INFO ChengdeMBP - [main]org.springframework.web.servlet.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
    2022-01-11 23:18:05.995  INFO ChengdeMBP - [main]org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@710f4dc7: startup date [Tue Jan 11 23:18:02 CST 2022]; root of context hierarchy
    2022-01-11 23:18:06.181  INFO ChengdeMBP - [main]org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
    2022-01-11 23:18:06.183  INFO ChengdeMBP - [main]org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
    2022-01-11 23:18:06.221  INFO ChengdeMBP - [main]org.springframework.web.servlet.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
    2022-01-11 23:18:06.221  INFO ChengdeMBP - [main]org.springframework.web.servlet.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
    2022-01-11 23:18:06.408  INFO ChengdeMBP - [main]org.springframework.jmx.export.annotation.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
    2022-01-11 23:18:06.426  INFO ChengdeMBP - [main]org.apache.coyote.http11.Http11NioProtocol : Starting ProtocolHandler ["http-nio-8080"]
    2022-01-11 23:18:06.483  INFO ChengdeMBP - [main]org.apache.tomcat.util.net.NioSelectorPool : Using a shared selector for servlet write/read
    2022-01-11 23:18:06.525  INFO ChengdeMBP - [main]org.springframework.boot.web.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
    2022-01-11 23:18:06.530  INFO ChengdeMBP - [main]com.space.log4j2.trial.Application : Started Application in 4.584 seconds (JVM running for 6.135)
    

    2、修改日志配置

    2.1 修改指定类的日志输出级别

    前面的例子中,可以看到好多org.springframework中类输出的info日志,可以单独将这些类的日志级别配置为warn。修改log4j2.xml

    <?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} - [%t]%c : %m%n
            </Property>
        </Properties>
        <Appenders>
            <!-- 引用前面的日志格式,将日志输出到控制台 -->
            <Console name="ConsoleAppender" target="SYSTEM_OUT" follow="true" >
                <PatternLayout pattern="${LOG_PATTERN}"/>
            </Console>
        </Appenders>
        <Loggers>
            <!-- 设置org.springframework包的日志输出级别为warn -->
            <Logger name="org.springframework" level="warn" additivity="false">
                <AppenderRef ref="ConsoleAppender"/>
            </Logger>
            <!-- 设置默认的日志输出级别 -->
            <Root level="info">
                <AppenderRef ref="ConsoleAppender" />
            </Root>
        </Loggers>
    </Configuration>
    

    修改后,启动运行,日志输出如下:

    2022-01-11 23:27:03.932  INFO ChengdeMBP - [main]com.space.log4j2.trial.Application : This is a info level log
    2022-01-11 23:27:03.939  WARN ChengdeMBP - [main]com.space.log4j2.trial.Application : This is a warn level log
    2022-01-11 23:27:03.939 ERROR ChengdeMBP - [main]com.space.log4j2.trial.Application : This is a error level log
    2022-01-11 23:27:03.939 FATAL ChengdeMBP - [main]com.space.log4j2.trial.Application : This is a fatal level log
    
      .   ____          _            __ _ _
     /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
    ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
     \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
      '  |____| .__|_| |_|_| |_\__, | / / / /
     =========|_|==============|___/=/_/_/_/
     :: Spring Boot ::        (v2.0.4.RELEASE)
    
    2022-01-11 23:27:04.798  INFO ChengdeMBP - [main]com.space.log4j2.trial.Application : Starting Application on ChengdeMBP with PID 1077 (/Users/chengxia/Developer/Java/JavaWeb/trial/target/classes started by chengxia in /Users/chengxia/Developer/Java/JavaWeb/trial)
    2022-01-11 23:27:04.799  INFO ChengdeMBP - [main]com.space.log4j2.trial.Application : No active profile set, falling back to default profiles: default
    2022-01-11 23:27:07.728  INFO ChengdeMBP - [main]org.apache.coyote.http11.Http11NioProtocol : Initializing ProtocolHandler ["http-nio-8080"]
    2022-01-11 23:27:07.751  INFO ChengdeMBP - [main]org.apache.catalina.core.StandardService : Starting service [Tomcat]
    2022-01-11 23:27:07.751  INFO ChengdeMBP - [main]org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.32
    2022-01-11 23:27:07.768  INFO ChengdeMBP - [localhost-startStop-1]org.apache.catalina.core.AprLifecycleListener : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [/Users/chengxia/Library/Java/Extensions:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java:.]
    2022-01-11 23:27:07.922  INFO ChengdeMBP - [localhost-startStop-1]org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
    2022-01-11 23:27:09.331  INFO ChengdeMBP - [main]org.apache.coyote.http11.Http11NioProtocol : Starting ProtocolHandler ["http-nio-8080"]
    2022-01-11 23:27:09.360  INFO ChengdeMBP - [main]org.apache.tomcat.util.net.NioSelectorPool : Using a shared selector for servlet write/read
    2022-01-11 23:27:09.407  INFO ChengdeMBP - [main]com.space.log4j2.trial.Application : Started Application in 5.313 seconds (JVM running for 6.798)
    

    2.2 将日志输出到文件

    修改配置文件log4j2.xml,将某些类的日志输出到文件。

    <?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} - [%t]%c : %m%n
            </Property>
            <!-- 定义日志存储的路径,不要配置相对路径 -->
            <property name="FILE_PATH" value="/Users/chengxia/Developer/Java/logs" />
            <property name="FILE_NAME" value="TestTest" />
        </Properties>
        <Appenders>
            <!-- 引用前面的日志格式,将日志输出到控制台 -->
            <Console name="ConsoleAppender" target="SYSTEM_OUT" follow="true" >
                <PatternLayout pattern="${LOG_PATTERN}"/>
            </Console>
            <!--
              这个会打印出所有的info及以下级别的信息,每次大小超过size,
              则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档
            -->
            <RollingFile name="RollingFileInfo" fileName="${FILE_PATH}/info.log" filePattern="${FILE_PATH}/${FILE_NAME}-INFO-%d{yyyy-MM-dd}_%i.log.gz">
                <!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch)-->
                <ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/>
                <PatternLayout pattern="${LOG_PATTERN}"/>
                <Policies>
                    <!--interval属性用来指定多久滚动一次,默认是1 hour-->
                    <TimeBasedTriggeringPolicy interval="1"/>
                    <SizeBasedTriggeringPolicy size="20MB"/>
                </Policies>
                <!-- DefaultRolloverStrategy属性如不设置,则默认为最多同一文件夹下7个文件开始覆盖 -->
                <DefaultRolloverStrategy max="15"/>
            </RollingFile>
    
            <!-- 这个会打印出所有的warn及以下级别的信息,每次大小超过size,则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档-->
            <RollingFile name="RollingFileWarn" fileName="${FILE_PATH}/warn.log" filePattern="${FILE_PATH}/${FILE_NAME}-WARN-%d{yyyy-MM-dd}_%i.log.gz">
                <!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch)-->
                <ThresholdFilter level="warn" onMatch="ACCEPT" onMismatch="DENY"/>
                <PatternLayout pattern="${LOG_PATTERN}"/>
                <Policies>
                    <!--interval属性用来指定多久滚动一次,默认是1 hour-->
                    <TimeBasedTriggeringPolicy interval="1"/>
                    <SizeBasedTriggeringPolicy size="20MB"/>
                </Policies>
                <!-- DefaultRolloverStrategy属性如不设置,则默认为最多同一文件夹下7个文件开始覆盖-->
                <DefaultRolloverStrategy max="15"/>
            </RollingFile>
    
            <!-- 这个会打印出所有的error及以下级别的信息,每次大小超过size,则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档-->
            <RollingFile name="RollingFileError" fileName="${FILE_PATH}/error.log" filePattern="${FILE_PATH}/${FILE_NAME}-ERROR-%d{yyyy-MM-dd}_%i.log.gz">
                <!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch)-->
                <ThresholdFilter level="error" onMatch="ACCEPT" onMismatch="DENY"/>
                <PatternLayout pattern="${LOG_PATTERN}"/>
                <Policies>
                    <!--interval属性用来指定多久滚动一次,默认是1 hour-->
                    <TimeBasedTriggeringPolicy interval="1"/>
                    <SizeBasedTriggeringPolicy size="20MB"/>
                </Policies>
                <!-- DefaultRolloverStrategy属性如不设置,则默认为最多同一文件夹下7个文件开始覆盖-->
                <DefaultRolloverStrategy max="15"/>
            </RollingFile>
        </Appenders>
        <Loggers>
            <!-- 设置org.springframework包的日志输出级别为warn -->
            <Logger name="org.springframework" level="warn" additivity="false">
                <AppenderRef ref="ConsoleAppender"/>
            </Logger>
            <!-- com.space包的日志输出级别为warn,输出到文件。additivity为"true"表示输出到文件的同时也输出到root logger -->
            <Logger name="com.space" level="info" additivity="true">
                <AppenderRef ref="RollingFileInfo"/>
                <AppenderRef ref="RollingFileWarn"/>
                <AppenderRef ref="RollingFileError"/>
            </Logger>
            <!-- 设置默认的日志输出级别 -->
            <Root level="info">
                <AppenderRef ref="ConsoleAppender" />
            </Root>
        </Loggers>
    </Configuration>
    

    启动运行之后,控制台日志输出如下:

    2022-01-11 23:40:31.672  INFO ChengdeMBP - [main]com.space.log4j2.trial.Application : This is a info level log
    2022-01-11 23:40:31.682  WARN ChengdeMBP - [main]com.space.log4j2.trial.Application : This is a warn level log
    2022-01-11 23:40:31.683 ERROR ChengdeMBP - [main]com.space.log4j2.trial.Application : This is a error level log
    2022-01-11 23:40:31.683 FATAL ChengdeMBP - [main]com.space.log4j2.trial.Application : This is a fatal level log
    
      .   ____          _            __ _ _
     /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
    ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
     \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
      '  |____| .__|_| |_|_| |_\__, | / / / /
     =========|_|==============|___/=/_/_/_/
     :: Spring Boot ::        (v2.0.4.RELEASE)
    
    2022-01-11 23:40:32.834  INFO ChengdeMBP - [main]com.space.log4j2.trial.Application : Starting Application on ChengdeMBP with PID 1194 (/Users/chengxia/Developer/Java/JavaWeb/trial/target/classes started by chengxia in /Users/chengxia/Developer/Java/JavaWeb/trial)
    2022-01-11 23:40:32.836  INFO ChengdeMBP - [main]com.space.log4j2.trial.Application : No active profile set, falling back to default profiles: default
    2022-01-11 23:40:35.117  INFO ChengdeMBP - [main]org.apache.coyote.http11.Http11NioProtocol : Initializing ProtocolHandler ["http-nio-8080"]
    2022-01-11 23:40:35.130  INFO ChengdeMBP - [main]org.apache.catalina.core.StandardService : Starting service [Tomcat]
    2022-01-11 23:40:35.130  INFO ChengdeMBP - [main]org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.32
    2022-01-11 23:40:35.142  INFO ChengdeMBP - [localhost-startStop-1]org.apache.catalina.core.AprLifecycleListener : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [/Users/chengxia/Library/Java/Extensions:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java:.]
    2022-01-11 23:40:35.262  INFO ChengdeMBP - [localhost-startStop-1]org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
    2022-01-11 23:40:36.451  INFO ChengdeMBP - [main]org.apache.coyote.http11.Http11NioProtocol : Starting ProtocolHandler ["http-nio-8080"]
    2022-01-11 23:40:36.478  INFO ChengdeMBP - [main]org.apache.tomcat.util.net.NioSelectorPool : Using a shared selector for servlet write/read
    2022-01-11 23:40:36.505  INFO ChengdeMBP - [main]com.space.log4j2.trial.Application : Started Application in 4.58 seconds (JVM running for 6.18)
    
    

    再看下文件中,也有对应的日志输出:

    ChengdeMBP:logs chengxia$ pwd
    /Users/chengxia/Developer/Java/logs
    ChengdeMBP:logs chengxia$ ls
    error.log   info.log    warn.log
    ChengdeMBP:logs chengxia$ cat info.log 
    2022-01-11 23:40:31.672  INFO ChengdeMBP - [main]com.space.log4j2.trial.Application : This is a info level log
    2022-01-11 23:40:31.682  WARN ChengdeMBP - [main]com.space.log4j2.trial.Application : This is a warn level log
    2022-01-11 23:40:31.683 ERROR ChengdeMBP - [main]com.space.log4j2.trial.Application : This is a error level log
    2022-01-11 23:40:31.683 FATAL ChengdeMBP - [main]com.space.log4j2.trial.Application : This is a fatal level log
    2022-01-11 23:40:32.834  INFO ChengdeMBP - [main]com.space.log4j2.trial.Application : Starting Application on ChengdeMBP with PID 1194 (/Users/chengxia/Developer/Java/JavaWeb/trial/target/classes started by chengxia in /Users/chengxia/Developer/Java/JavaWeb/trial)
    2022-01-11 23:40:32.836  INFO ChengdeMBP - [main]com.space.log4j2.trial.Application : No active profile set, falling back to default profiles: default
    2022-01-11 23:40:36.505  INFO ChengdeMBP - [main]com.space.log4j2.trial.Application : Started Application in 4.58 seconds (JVM running for 6.18)
    ChengdeMBP:logs chengxia$ cat warn.log 
    2022-01-11 23:40:31.682  WARN ChengdeMBP - [main]com.space.log4j2.trial.Application : This is a warn level log
    2022-01-11 23:40:31.683 ERROR ChengdeMBP - [main]com.space.log4j2.trial.Application : This is a error level log
    2022-01-11 23:40:31.683 FATAL ChengdeMBP - [main]com.space.log4j2.trial.Application : This is a fatal level log
    ChengdeMBP:logs chengxia$ cat error.log 
    2022-01-11 23:40:31.683 ERROR ChengdeMBP - [main]com.space.log4j2.trial.Application : This is a error level log
    2022-01-11 23:40:31.683 FATAL ChengdeMBP - [main]com.space.log4j2.trial.Application : This is a fatal level log
    ChengdeMBP:logs chengxia$ 
    

    3、log4j日志格式配置

    如下参考:

    %p:输出日志信息的优先级,即DEBUG,INFO,WARN,ERROR,FATAL。 
    %d:输出日志时间点的日期或时间,默认格式为ISO8601,也可以在其后指定格式,如:%d{yyyy/MM/dd HH:mm:ss,SSS}。 
    %r:输出自应用程序启动到输出该log信息耗费的毫秒数。 
    %t:输出产生该日志事件的线程名。 
    %l:输出日志事件的发生位置,相当于%c.%M(%F:%L)的组合,包括类全名、方法、文件名以及在代码中的行数。例如:test.TestLog4j.main(TestLog4j.java:10)。 
    %c:输出日志信息所属的类目,通常就是所在类的全名。 
    %M:输出产生日志信息的方法名。 
    %F:输出日志消息产生时所在的文件名称。 
    %L::输出代码中的行号。 
    %m::输出代码中指定的具体日志信息。 
    %n:输出一个回车换行符,Windows平台为”rn”,Unix平台为”n”。 
    %x:输出和当前线程相关联的NDC(嵌套诊断环境),尤其用到像java servlets这样的多客户多线程的应用中。 
    %%:输出一个”%”字符。 
    另外,还可以在%与格式字符之间加上修饰符来控制其最小长度、最大长度、和文本的对齐方式。如: 
    1) c:指定输出category的名称,最小的长度是20,如果category的名称长度小于20的话,默认的情况下右对齐。 
    2)%-20c:”-“号表示左对齐。 
    3)%.30c:指定输出category的名称,最大的长度是30,如果category的名称长度大于30的话,就会将左边多出的字符截掉,但小于30的话也不会补空格。
    

    参考资料

    log4j日志配置(超详细)

    相关文章

      网友评论

          本文标题:SpringBoot中log4j2的使用和配置

          本文链接:https://www.haomeiwen.com/subject/gezicrtx.html