SpringBoot Log Processing of Logback


Log Processing is an official project of the essential functions, to be able to log according to time, type and other factors, to save the specified log according to the specified format to help us observe the operation of the program, locate the program bug.

SpringBoot recommended for use Logback logging framework.

This section sample project in https://github.com/laolunsi/spring-boot-examples


slf4j: a unified facade abstract for all types of Java logging framework.

Common java logging framework: java.util.logging, log4j, logback, commons-logging

logback is a new generation of log4j logging framework developed, the most widely used. SpringBoot default logback, the default level of INFO

Logback:

Log load order: logback.xml -> application.properties -> logback-spring.xml


A log level

log4j defined log level: debug / info / warn / error / fatal

warn, potential errors; error, the error could cause the program to quit; fatal, serious errors, the program will quit

There are two special levels: OFF- highest level, ALL- lowest level

log4j is recommended that only debug / info / warn / error of four levels

Log Level: ERROR -> WARN -> INFO -> DEBUG

The logging level is configured INFO, INFO and above the level of the log output, and lower than the INFO level log (debug log) is not output.


Two, SpringBoot introduced logger

Direct introduction:

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-logging</artifactId>
      <version>2.1.11.RELEASE</version>
      <scope>compile</scope>
    </dependency>

Indirect introduction:

Introducing spring-boot-starter, it will automatically introduce spring-boot-starter-logging

Introducing spring-boot-starter-web, it will automatically introduce spring-boot-starter


Third, the configuration logback by springboot profile

Configure output log to a file:

logging:
  file: logback-demo.log # 输出到项目目录下

The default is the summed output, that is, before the project does not delete the log file every time you start, nor will clear the log file currently in use, but under a separate line.

Log Level:logging.level.*: level-name

* Refers to the package name or log name, log name as the root, a system log

level-name refers to the log level, conventional debug / info / warn / error

such as:

logging:
  level:
    com.example.logbackdemo: debug # 指定包下日志以debug级别输出
    #root: warn # root日志以warn级别输出,不要用debug级别!!---会卡的!

Fourth, logback custom configuration file by XMl

The above configuration does save the log to a file, but not so useful for the actual project.

For example: The log file is very large, the size of the logs generated daily in hundreds of MB, a single file can handle it? Log categorical need to save how to do it? How do custom log format it?

These are the questions.

Fortunately, including logging framework, including the most logback provides profiles feature, the most common is to use xml files for configuration.

Logging framework default configuration file:

  • Logback:logback-spring.xml, logback-spring.groovy, logback.xml, logback.groovy
  • Log4j:log4j-spring.properties, log4j-spring.xml, log4j.properties, log4j.xml
  • Log4j2:log4j2-spring.xml, log4j2.xml
  • JDK (Java Util Logging):logging.properties

Log load order: logback.xml -> application.properties -> logback-spring.xml

logback framework:

Specify profile xxx.xml: recommended logback-spring.xml, can also logging.config = classpath in the application.

Example:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <contextName>logback-spring-demo-dev</contextName>
    <property name="pattern" value="%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg %n"/>
    <property name="pattern-color" value="%yellow(%d{yyyy-MM-dd HH:mm:ss.SSS}) [%thread] %highlight(%-5level) %green(%logger{50}) - %highlight(%msg) %n"/>
    <property name="LOG_HOME" value="logs"/>

    <!-- 控制台输出 -->
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <pattern>${pattern}</pattern>
        </encoder>
    </appender>

    <!-- 控制台输出-带颜色 -->
    <appender name="CONSOLE-WITH-COLOR" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <pattern>${pattern-color}</pattern>
        </encoder>
    </appender>

    <!-- 文件输出 -->
    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${LOG_HOME}/all.%d.%i.log</fileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>10MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
            <maxHistory>30</maxHistory>
        </rollingPolicy>

        <encoder>
            <pattern>${pattern}</pattern>
        </encoder>
    </appender>


    <root level="INFO">
        <appender-ref ref="CONSOLE-WITH-COLOR"/>
        <appender-ref ref="FILE"/>
    </root>

    <logger name="com.example.logbackdemo.IndexAction" level="info" additivity="false">
        <appender-ref ref="CONSOLE"/>
    </logger>

</configuration>

The following describe specific configuration items logback.xml in:

There are two properties and three nodes:

  1. Two properties: contextName and property
  2. Three nodes: appender, root, logger

4.1 contextName property

contextName: log name, can be used to refer to% contextName

If there logback.xml and logback-spring.xml simultaneously, or exist logback.xml and custom configuration file will be loaded logback.xml, and then load the specified application in accordance with the configuration profile, or load logback-spring, xml . If contextName both profiles are different, the error will be:

ERROR in ch.qos.logback.classic.joran.action.ContextNameAction - Failed to rename context [logback-demo] as [logback-spring-demo-dev] java.lang.IllegalStateException: Context has been already given a name

4.2 property property

property can be used to customize the tag attributes, such as defining a , $ {LOG_HOME} is then used to reference it


4.3 appender node

appender adder means, where the log can be understood as a renderer. For example, rendering console log into a certain format, rendering the log file to another format.

appender name and class has two attributes, there rollingPolicy encoder and two child nodes.

name indicates that the renderer name, class represents the output of strategies used, a common policy console output and file output policy.

4.3.1 appender console output

<property name="pattern" value="%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg %n"/>

<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
    <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
    <pattern>${pattern}</pattern>
  </encoder>
</appender>

encoder output format represents, as explained below:

% D represents the time

% Thread represents the thread name

% -5level represents the log level, allowing the output to five characters in length

% Logger {50} represented by a particular log output, such as the class name in parentheses represents the length

% Msg shows a specific log messages, is logger.info ( "xxx") of xxx

% N represents a newline

Highlight colors may also be defined, such as speaking pattern is defined as follows:

<property name="pattern-color" value="%yellow(%d{yyyy-MM-dd HH:mm:ss.SSS}) [%thread] %highlight(%-5level) %green(%logger{50}) - %highlight(%msg) %n"/>

I.e. using the% color (xxx) to specify the color of a corresponding column output can be realized console output color highlighting.

4.3.2 Input file appender

The main configuration file output comprising: a specified output format log file to a specified folder, the name of the file can be configured maximum size, storage time

E.g:

<property name="LOG_HOME" value="logs"/>
<property name="pattern" value="%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg %n"/>

<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
  <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
    <fileNamePattern>${LOG_HOME}/all.%d.%i.log</fileNamePattern>
    <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
        <maxFileSize>10MB</maxFileSize>
    </timeBasedFileNamingAndTriggeringPolicy>
    <maxHistory>30</maxHistory>
  </rollingPolicy>

  <encoder>
    <pattern>${pattern}</pattern>
    </encoder>
</appender>

The main contents of the above configuration is: to specify the format of the output to the log file in the logs file, the file name format is specified as logs / all date index number .log, the maximum log file size is 10MB, beyond the new file is created. Keep log files for thirty days

Index increments from 0

rollingPolicy rough rolling means, the specific configuration described above.

Size limit on the log file can also be used 1GB Configuration.


4.4 root node - enable the configuration

root node is actually a configuration which appender is enabled, you can add multiple appender.

such as:

<root level="INFO">
    <appender-ref ref="CONSOLE-WITH-COLOR"/>
  <appender-ref ref="FILE"/>
</root>

It represents the level for the info level to enable the renderer CONSOLE-WITH-COLOR and FILE.

When the output log, according to CONSOLE console output format defined in accordance with this configuration, the log file to output according to CONSOLE-WITH-COLOR configuration.


4.5 logger node

Adding configure a single package or class:

    <!-- logger节点可以指定具体包或类的日志配置 -->
    <!-- name属性为必选,指定要配置的包或类,level和additivity为可选,有缺省值 -->
    <!-- level表示日志级别,这里配置info级别,表示info及以上级别的日志被输出 -->
    <!-- additivity表示日志是否传递到上一级,默认为true -->
    <logger name="com.example.logbackdemo.IndexAction" level="info" additivity="false">
        <appender-ref ref="CONSOLE"/>
    </logger>

Here we add a test interface categories:

@RestController
@RequestMapping(value = "log")
public class IndexAction {

    private Logger logger = LoggerFactory.getLogger(IndexAction.class);

    @GetMapping(value = "")
    public String testLoggerTag() {
        logger.debug("测试logger标签");
        logger.info("测试logger标签");
        logger.warn("测试logger标签");
        logger.error("测试logger标签");
        return "this is spring-boot-logback-demo projects.";
    }
}

Start the project, call interface test:
file

We found IndexAction console log output class is no color, i.e. logger configuration effective. After the set to true additivity, the console output twice found the same content.
file

In addition, there is a configuration file used to specify the corresponding springProfile springboot log tab configuration, the application will be mentioned below.


4.6 Enabling those designated log configuration

  1. springboot specify which enabled xml

    Xml which we can use as a logger configuration specified in the configuration file springboot, such as: logging.config = classpath: logback-spring-dev.xml.

    If not specified, according to logback.xml-> application.yml-> logback-spring.xml order to find whether there is a default configuration.

  2. Under xml tags used springProfile environment which specify which settings to use

    We can also xml configuration file to specify which configuration to use in the environment in which a particular log, such as:

    <springProfile name="local,dev">
     <root level="INFO">
         <appender-ref ref="CONSOLE-WITH-COLOR"/>
         <appender-ref ref="FILE"/>
     </root>
    </springProfile>
    
    <springProfile name="prod">
     <root level="INFO">
         <appender-ref ref="CONSOLE-WITH-COLOR"/>
         <appender-ref ref="FILE"/>
     </root>
    </springProfile>
    

In this case, we do not recommend more xml files, use a default logback-spring.xml can be.


reference:

https://mrbird.cc/Spring-Boot-logback.html

https://www.jianshu.com/p/b3dedb8fb61e

https://blog.csdn.net/lchq1995/article/details/80080642

https://blog.csdn.net/Rogger_chen/article/details/50587920

Guess you like

Origin www.cnblogs.com/eknown/p/12010502.html