spring boot logback

Foreword

Under today to introduce how to configure Spring Boot log logback, I just learned, is with the following questions to check data, How about you

  • How to introduce log?
  • How to log output format and output configuration?
  • How to use the code?

text

Spring Boot used in all internal logs Commons Logging , but the default configuration also provides support for common log, such as: the Java Util Logging , Log4JLog4J2 and Logback . Each Logger can use the console output log file or content through configuration.

The default log Logback

SLF4J --simple Logging Facade the For  Java , it is a unified framework for all types of Java logging Facade abstract. Many Java logging framework - commonly used java.util.logginglog4jlogback, commons-logging, the Spring Framework using Jakarta Commons Logging API (JCL). The SLF4J defines a uniform log abstract interface, and a real log realization is decided at runtime - it provides a binding framework for all types of logging.

Logback is a new generation of logging framework log4j framework of development, it is more efficient, able to adapt to many of the operating environment, while natural support SLF4J.

By default, Spring Boot Logback will be used to log and to the console with the INFO level. When you run the applications and other examples, you should have seen a lot of INFO level logging.

Can be seen from the figure, the log output content elements as follows:

  • Date Time: accurate millisecond
  • Log levels: ERROR, WARN, INFO, DEBUG or TRACE
  • Process ID
  • : Delimiter --- to identify the beginning of the actual log
  • Thread name: square brackets (console output may be truncated)
  • Logger name: commonly used source class name
  • Log content

Add Log dependence

If the added dependency maven spring-boot-starter-logging:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-logging</artifactId>
</dependency>

 

So, our Spring Boot application will automatically use logback as application logging framework, Spring Boot startup, initialization and used according to the situation by the org.springframework.boot.logging.Logging-Application-Listener.

But then, we do not need the actual development directly add the dependency, you will find spring-boot-starter which contains a spring-boot-starter-logging, the content is dependent on Spring Boot default logging framework logback. The examples of bloggers this project is based on one of the project useful to the Thymeleaf, and Thymeleaf rely contain spring-boot-starter, eventually I just introduced Thymeleaf can be.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

This can be seen particularly in FIG.

The default configuration properties support

Spring Boot provides us with a lot of the default log configuration, so long as the spring-boot-starter-logging as a dependency added to the classpath the current application, the "out of the box."
Here are some related properties in application.properties log can be configured.

Console output

The logging level from low to high into TRACE <DEBUG <INFO <WARN < ERROR <FATAL, if set to WARN, the information will not be lower than the WARN output.
Spring Boot default configuration ERROR, WARNand INFOlevel of log output to the console. You can also enable "Debug" mode by starting your application -debug flag (when developing recommendations open), Jieke two ways:

  • After running the command added to --debugsigns, such as:$ java -jar springTest.jar --debug
  • In application.propertiesthe configuration debug=true, when the property is set to true, the core Logger (containing embedded container, hibernate, spring) output will be more, but the log of your own applications and does not output to DEBUG level.

File Output

By default, Spring Boot the log output to the console, not to the log file. If you want to write the log file other than the console output, you need to set logging.file or logging.path property in application.properties in.

  • logging.file, settings file, can be an absolute path, or a relative path. Such as:logging.file=my.log
  • logging.path, set the directory is created in the directory spring.log file and write the contents of the log, such as:logging.path=/var/log

If only logging.file, xxx.log generates a log file in the current path of the project.
If only logging.path, in / var / log folder generating a log file spring.log

Note: Both can not be used, should use, take effect only logging.file

By default, it will cut the size of the log file reaches 10MB points once, generate new log file, the default level is: ERROR, WARN, INFO

Level control

All logging system supported by the record level can be set in a Spring environment (e.g., in the application.properties)
format is: '. Logging.level * = LEVEL'

  • logging.level: Log level control prefix *is the package name or the name of Logger
  • LEVEL:选项TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF

For example:

  • logging.level.com.dudu=DEBUG: com.duduAll class under the package to DEBUG level output
  • logging.level.root=WARN: Root log level WARN output

Custom log configuration

Since the log service is generally created before ApplicationContext is initialized, and it must not be controlled by the Spring configuration file. Therefore still be well supported by the log control and management system properties and traditional Spring Boot external configuration files.

Depending on the logging system, you can configure the file name follows the rules of the organization, can be loaded correctly:

  • Logback:logback-spring.xmllogback-spring.groovylogback.xmllogback.groovy
  • Laog4j: log4j-spring.propertieslog4j-spring.xmllog4j.propertieslog4j.xml
  • Log4j2:log4j2-spring.xmllog4j2.xml
  • JDK (Java Util Logging):logging.properties

Spring Boot priority official recommended to use with -springthe file name as your log configuration (such as using logback-spring.xml, instead logback.xml), named logback-spring.xml log configuration file, spring boot can be added to it some spring boot-specific configuration items ( mentioned below).

The above is the default naming convention, and on src/main/resourcesthe following can be.

That is if you want complete control over the configuration logs, but do not want to use logback.xmlas the Logbackconfiguration name, you can specify a custom name attribute by logging.config:

1
logging.config=classpath:logging-config.xml

 

While the general does not need to change the name of the configuration file, but if you want to run for a different day using different Profile
Configuration Chi, this feature would be useful.

Let us look at a common example of logback-spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration  scan="true" scanPeriod="60 seconds" debug="false">
    <contextName>logback</contextName>
    <property name="log.path" value="E:\\test\\logback.log" />
    <!--输出到控制台-->
    <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
       <!-- <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>ERROR</level>
        </filter>-->
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} %contextName [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <!--输出到文件-->
    <appender name="file" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${log.path}</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>logback.%d{yyyy-MM-dd}.log</fileNamePattern>
        </rollingPolicy>
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} %contextName [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <root level="info">
        <appender-ref ref="console" />
        <appender-ref ref="file" />
    </root>

    <!-- logback为java中的包 -->
    <logger name="com.dudu.controller"/>
    <!--logback.LogbackDemo:类的全路径 -->
    <logger name="com.dudu.controller.LearnController" level="WARN" additivity="false">
        <appender-ref ref="console"/>
    </logger>
</configuration>

Root <configuration>contains properties

  • scan: When this property is set to true, if the profile change, will be reloaded, the default value is true.
  • scanPeriod: Set if there are modified profiles monitoring interval, if the time unit is not given, the default milliseconds. When the scan is true, this property take effect. The default interval is 1 minute.
  • debug: When this property is set to true, will print logback internal log information, real-time view logback running. The default value is false.

Root <configuration>child nodes:
<configuration>following a total of two attributes, three sub-nodes, namely:

A property: set the context name<contextName>

Each logger is associated to the logger context, the default context name is "default". However, other names may be used provided, for distinguishing between different recording applications. Once set, can not be modified, the log may be printed by context name% contextName.

1
<contextName>logback</contextName>

 

Properties Two: Set the variable<property>

Tag is used to define the variable value, there are two attributes, name and value; wherein the value of the name is the name of the variable, the value of the variable value defined in the value. It will be inserted into logger value defined by the context. After the defined variables can be made "$ {}" to use variables.

1
<property name="log.path" value="E:\\logback.log" />

 

A child node<appender>

appender used to format log output node, there are two attributes name and class, class is used to specify which output policy, is commonly used tactics console output and file output policy.

##### console output ConsoleAppender:

<!--输出到控制台-->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
    <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
        <level>ERROR</level>
    </filter>
    <encoder>
        <pattern>%d{HH:mm:ss.SSS} %contextName [%thread] %-5level %logger{36} - %msg%n</pattern>
    </encoder>
</appender>

 

<encoder>It represents the log Code:

  • %d{HH: mm:ss.SSS}- Log output time
  • %thread- the name of the process output log, which is useful in Web applications, and asynchronous tasking
  • %-5level- the log level, and uses five characters aligned to the left
  • %logger{36}- the name of the log exporter
  • %msg- log messages
  • %n- newline platform

ThresholdFilter interceptors defined for the system, for example, we used to filter out ThresholdFilter ERROR below the level of logging is not output to a file. If you do not remember to comment out, or you'll find no logging console ~

Output to file RollingFileAppender

Another common log output to a file, with the application of more and more time running, the log will grow more and more, they will be output to the same file is not a good idea. RollingFileAppenderFor slicing the log file:

<!--输出到文件-->
<appender name="file" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>${log.path}</file>
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        <fileNamePattern>logback.%d{yyyy-MM-dd}.log</fileNamePattern>
        <maxHistory>30</maxHistory>
        <totalSizeCap>1GB</totalSizeCap>
    </rollingPolicy>
    <encoder>
        <pattern>%d{HH:mm:ss.SSS} %contextName [%thread] %-5level %logger{36} - %msg%n</pattern>
    </encoder>
</appender>

 

Where it is important rollingPolicydefinitions, the above example <fileNamePattern>logback.%d{yyyy-MM-dd}.log</fileNamePattern>is defined segmented patterns logs - each day archive log to a file, <maxHistory>30</maxHistory>it indicates that only retains the last 30 days of logs to prevent the log from filling up the entire disk space. Similarly, it can be used %d{yyyy-MM-dd_HH-mm}to define the precise points to the log mode segmentation. <totalSizeCap>1GB</totalSizeCap>To specify a log file size limit, for example, is set to 1GB, then to this value, it will delete the old log.

Two child nodes<root>

Required root node is a node, is used to specify the most basic log output level, a level only attribute.

  • level: the level used to set the print, case insensitive: TRACE, DEBUG, INFO, WARN , ERROR, ALL and OFF, or can not be set INHERITED synonymous NULL.
    The default is DEBUG.
    Can contain zero or more elements, identifies the appender will be added to this loger.
  • <root level="debug">
        <appender-ref ref="console" />
        <appender-ref ref="file" />
    </root>

     

Three child nodes<loger>

<loger>To set the logging level to print one specific packet or a certain class, and the designation <appender>. <loger>Only one name attribute, an optional level and an optional addtivity property.

  • name: Specifies a particular packet or specifically bound by this loger a certain class.
  • level: To set the level of printing, its case is: TRACE, DEBUG, INFO, WARN, ERROR, ALL and OFF, there is a Japanese popular value INHERITED synonyms or NULL, on behalf of the higher level of enforcement. If this property is not set, then the current level loger will inherit superiors.
  • addtivity: Whether print information passed to the higher loger. The default is true.

loger when in actual use, there are two cases
to look at how to use the code

package com.dudu.controller;
@Controller
public class LearnController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> login(HttpServletRequest request, HttpServletResponse response){
        //日志级别从低到高分为TRACE < DEBUG < INFO < WARN < ERROR < FATAL,如果设置为WARN,则低于WARN的信息都不会输出。
        logger.trace("日志输出 trace");
        logger.debug("日志输出 debug");
        logger.info("日志输出 info");
        logger.warn("日志输出 warn");
        logger.error("日志输出 error");
        Map<String,Object> map =new HashMap<String,Object>();
        String userName=request.getParameter("userName");
        String password=request.getParameter("password");
        if(!userName.equals("") && password!=""){
            User user =new User(userName,password);
            request.getSession().setAttribute("user",user);
            map.put("result","1");
        }else{
            map.put("result","0");
        }
        return map;
    }
}

 

This is the way to judge a login, we introduce log, and print different levels of logging, then take a look at what kinds of print log level according to logback-spring.xml configuration.

The first: with loger configuration, no level is specified, do not specify the appender

 
<logger name="com.dudu.controller"/>

 

<logger name="com.dudu.controller" />All classes will print a log under the control of controller package, but did not level with print settings, so inherit his superiors log level "info";
not set addtivity, the default is true, print this information is transmitted to the higher loger ;
not set appender, this loger itself does not print any information.
<root level="info">The print root level is set to "info", specifies the name to "console" the appender.

When the login method performed com.dudu.controller.LearnController class, LearnController com.dudu.controller in the package, it is first executed <logger name="com.dudu.controller"/>, the transmission level is log information "info" and greater than "info" to the root, does not per se printing;
root subordinate to the transfer of information, to the configured named "console" the appender process, "console" appender information printed to the console;

Print results are as follows:

1
2
3
16:00:17.407 logback [http-nio-8080-exec-8] INFO  com.dudu.controller.LearnController - 日志输出 info
16:00:17.408 logback [http-nio-8080-exec-8] WARN  com.dudu.controller.LearnController - 日志输出 warn
16:00:17.408 logback [http-nio-8080-exec-8] ERROR com.dudu.controller.LearnController - 日志输出 error

 

The second: loger with multiple configurations specified level, the specified appender

1
2
3
4
<!--logback.LogbackDemo:类的全路径 -->
<logger name="com.dudu.controller.LearnController" level="WARN" additivity="false">
    <appender-ref ref="console"/>
</logger>

 

控制com.dudu.controller.LearnController类的日志打印,打印级别为“WARN”;
additivity属性为false,表示此loger的打印信息不再向上级传递;
指定了名字为“console”的appender;

这时候执行com.dudu.controller.LearnController类的login方法时,先执行<logger name="com.dudu.controller.LearnController" level="WARN" additivity="false">,
将级别为“WARN”及大于“WARN”的日志信息交给此loger指定的名为“console”的appender处理,在控制台中打出日志,不再向上级root传递打印信息。
打印结果如下:

1
2
16:00:17.408 logback [http-nio-8080-exec-8] WARN  com.dudu.controller.LearnController - 日志输出 warn
16:00:17.408 logback [http-nio-8080-exec-8] ERROR com.dudu.controller.LearnController - 日志输出 error

 

当然如果你把additivity=”false”改成additivity=”true”的话,就会打印两次,因为打印信息向上级传递,logger本身打印一次,root接到后又打印一次。

多环境日志输出

据不同环境(prod:生产环境,test:测试环境,dev:开发环境)来定义不同的日志输出,在 logback-spring.xml中使用 springProfile 节点来定义,方法如下:

文件名称不是logback.xml,想使用spring扩展profile支持,要以logback-spring.xml命名

<!-- 测试环境+开发环境. 多个使用逗号隔开. -->
<springProfile name="test,dev">
    <logger name="com.dudu.controller" level="info" />
</springProfile>
<!-- 生产环境. -->
<springProfile name="prod">
    <logger name="com.dudu.controller" level="ERROR" />
</springProfile>

可以启动服务的时候指定 profile (如不指定使用默认),如指定prod 的方式为:
java -jar xxx.jar –spring.profiles.active=prod
关于多环境配置可以参考

动态配置日志输入文件目录:

可以对logback中的配置文件 log.path进行动态设置。 

对项目进行打包的时候,可以通过maven 的-D 参数进行设置

多线程下的日志追踪(mdc)

MDC(Mapped Diagnostic Context,映射调试上下文)是 log4j 和 logback 提供的一种方便在多线程条件下记录日志的功能。某些应用程序采用多线程的方式来处理多个用户的请求。在一个用户的使用过程中,可能有多个不同的线程来进行处理。典型的例子是 Web 应用服务器。当用户访问某个页面时,应用服务器可能会创建一个新的线程来处理该请求,也可能从线程池中复用已有的线程。在一个用户的会话存续期间,可能有多个线程处理过该用户的请求。这使得比较难以区分不同用户所对应的日志。当需要追踪某个用户在系统中的相关日志记录时,就会变得很麻烦。

  一种解决的办法是采用自定义的日志格式,把用户的信息采用某种方式编码在日志记录中。这种方式的问题在于要求在每个使用日志记录器的类中,都可以访问到用户相关的信息。这样才可能在记录日志时使用。这样的条件通常是比较难以满足的。MDC 的作用是解决这个问题。

  MDC 可以看成是一个与当前线程绑定的哈希表,可以往其中添加键值对。MDC 中包含的内容可以被同一线程中执行的代码所访问。当前线程的子线程会继承其父线程中的 MDC 的内容。当需要记录日志时,只需要从 MDC 中获取所需的信息即可。MDC 的内容则由程序在适当的时候保存进去。对于一个 Web 应用来说,通常是在请求被处理的最开始保存这些数据。

使用:

java:
MDC.put("traceId", requestId);

pattern:
<pattern>%d{yyyy-MM-dd HH:mm:ss} %X{traceId} %-5level %logger{36} | %msg%n</pattern>

使用%X 获取traceId


filter:

对日志输出进行过滤,详见 https://www.cnblogs.com/drizzlewithwind/p/6045435.html

总结

到此为止终于介绍完日志框架了,平时使用的时候推荐用自定义logback-spring.xml来配置,代码中使用日志也很简单,类里面添加private Logger logger = LoggerFactory.getLogger(this.getClass());即可

 

转载:https://blog.csdn.net/c3618392/article/details/78934904

Guess you like

Origin blog.csdn.net/qq_39158142/article/details/90108910