SpringBoot gracefully configuration log

This paper to introduce SpringBoot how gracefully logging by sl4j logging component. In fact, our entry- JAVA first line of code is the line of the log, that you are still using the System.out.println("Hello,小明!")log it?

I've been through logging component

I came into contact with the logging component is Log4j

Log4j as an Apache open source project, through the use of Log4j , we can control the destination log information delivery is the console, files, etc. we expect output to where it is; we can also control the output format of each log; by defined level of each log information, we can more carefully control the build process logs.

We can be flexibly configured above by a profile without the need to modify application code. Log4j as the first time as a more popular logging frameworks, to us in application development and maintenance has brought great convenience.

Today, however, still slowly down the "altar" mean, gradually Logback alternative, no trace of her thousands of Baidu, the original Logback is an upgraded version , relatively Log4j terms have more improvements and developers turned out to be in the same class men (in fact, written by one person)!

Nova Logback

Logback mainly has the following characteristics:

  1. Faster execution: Based on our previously Log4j work on, Logback rewrite the internal implementation, in certain scenarios above, or even 10 times faster than the previous speed. Ensuring Logback components more quickly, while at the same time more and less memory required;
  2. Fully tested: Logback After a few years, the number of countless hours of testing. Although Log4j also tested, but Logback test more fully, with Log4j not on the same level. We believe that this is the people's choice Logback instead Log4j most important reason. Who does not want even under harsh conditions, your logging framework remains stable and reliable it?
  • It consists of three modules
    • logback-core
    • logback-classic
    • logback-access

logback-coreInfrastructure other modules, other modules build on it, obviously, logback-coreprovides a number of key common mechanisms. logback-classicEquivalent to the status and role Log4J, it is also considered Log4Jan improved version, and it implements a simple logging facade SLF4J; but logback-accessmainly as a the Servletmodule container interaction, for example tomcat, or jettyto provide some of HTTPthe relevant access functions.

What is it Sl4J?

SLF4J : the Simple Logging the Facade at The java for the Java that is simply log facade

The short answer is to say slf4j is a series of log interfaces, slf4j as abstract behavior of a log exists, but does not provide a true realization.

slf4j provides a unified interface to a variety of logging framework allows the user to log unified interface, dynamically determines the frame to be used to achieve such Logback , Log4j , Common the logging- like framework implement these interfaces.

How do I configure the log?

Is obvious, Springboot default logging framework is Logback . The flow, in the project, we use Logback , in fact, simply add a configuration file (customize your configuration) can be.

Detailed profiles

Streamlined profile structure is shown below

<configuration scan="true" scanPeriod="60 seconds" debug="false">  
         <!-- 属性文件:在properties/yml文件中找到对应的配置项 -->
    <springProperty scope="context" name="logging.path" source="logging.path"/>
    <contextName>程序员小明</contextName> 
    
    <appender>
        //xxxx
    </appender>   
    
    <logger>
        //xxxx
    </logger>
    
    <root>             
       //xxxx
    </root>  
</configuration>  

By default this file is called in springboot in logback-spring.xml , we just create a file with the same name on the resources below to validate the configuration.

Each explanation of the configuration is as follows:

contextName

Each loggeris associated to the loggercontext, the default context name “default”. You may be used contextNameother name tags provided, to distinguish between different applications for recording

property

Tag is used to define the value of a variable, propertytag has two attributes, nameand value; wherein namethe value is the name of the variable, valuethe value of the variable value is defined. By propertyit is inserted to a value defined loggercontext. After the defined variables can be made "$ {name}" to use variables. As above xmlshown.

logger

Used to set a certain packet or a certain particular class level, and a print log specified appender.

root

Root logger, also a logger, and only one level property

appender

Responsible for writing component log

The type of appender
  • ConsoleAppender: add a log to the console
  • FileAppender: to add to the log file
  • RollingFileAppender: rolling log file, logging to the specified file first, when a condition matches, logging to other files. It is a subclass of FileAppender

filter

filter is actually a sub-element appender inside. It exists as a filter, a filter will perform a return three enumerated value DENY, NEUTRAL, ACCEPT is.

  • DENY: log will be discarded immediately after other filters no longer

  • NEUTRAL: an ordered list of next filter then processed through a log

  • ACCEPT: the log will be processed immediately without undergoing the remaining filter

    There are several filters

    ThresholdFilter

    Threshold filter, to filter out below a specified threshold log. When the log level is equal to or higher than the critical value, the filter returned NEUTRAL; and when the threshold level is lower than the log, the log will be rejected.

    <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
        <level>INFO</level>
    </filter>
    LevelFilter

    Level filters, filter based on log level. If the level is equal to the log level configuration, based on the filter onMath(in accordance with the conditions for operation of the filter configuration), and onMismatch(for configuration does not match the filter) to accept or reject the log.

    <filter class="ch.qos.logback.classic.filter.LevelFilter">   
      <level>INFO</level>   
      <onMatch>ACCEPT</onMatch>   
      <onMismatch>DENY</onMismatch>   
    </filter> 

Projects

ready

A simple normal Springboot project

Profiles

application.yml

Simple configuration of the log, we can directly in application.ymla simple configuration, such as the position of the print output level and the log indicates log

logging:
  level:
    root: info
  path: ./logs

It may also be used according to the specified environment configuration profile points, default logback-spring.xml

logging:
  level:
    root: info
  path: ./logs
  config: classpath:/logback-dev.xml

logback-spring.xml

In the resources the new directory logback-spring.xml file, for example a simple demand, if in the project, if we need to specify a log output format and output according to the log level to a different file, you can configure the following:

<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
    <!-- 属性文件:在properties文件中找到对应的配置项 -->
    <springProperty scope="context" name="logging.path" source="logging.path"/>
    <contextName>xiaoming</contextName>
    <appender name="consoleLog" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <!--格式化输出(配色):%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
            <pattern>%yellow(%d{yyyy-MM-dd HH:mm:ss}) %red([%thread]) %highlight(%-5level) %cyan(%logger{50}) - %magenta(%msg) %n
            </pattern>
            <charset>UTF-8</charset>
        </encoder>
    </appender>

    <!--根据日志级别分离日志,分别输出到不同的文件-->
    <appender name="fileInfoLog" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>ERROR</level>
            <onMatch>DENY</onMatch>
            <onMismatch>ACCEPT</onMismatch>
        </filter>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <pattern>
                %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{50} - %msg%n
            </pattern>
            <charset>UTF-8</charset>
        </encoder>
        <!--滚动策略-->
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!--按时间保存日志 修改格式可以按小时、按天、月来保存-->
            <fileNamePattern>${logging.path}/xiaoming.info.%d{yyyy-MM-dd}.log</fileNamePattern>
            <!--保存时长-->
            <MaxHistory>90</MaxHistory>
            <!--文件大小-->
            <totalSizeCap>1GB</totalSizeCap>
        </rollingPolicy>
    </appender>

    <appender name="fileErrorLog" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>ERROR</level>
        </filter>
        <encoder>
            <pattern>
                %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{50} - %msg%n
            </pattern>
        </encoder>
        <!--滚动策略-->
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!--路径-->
            <fileNamePattern>${logging.path}/xiaoming.error.%d{yyyy-MM-dd}.log</fileNamePattern>
            <MaxHistory>90</MaxHistory>
        </rollingPolicy>
    </appender>
    <root level="info">
        <appender-ref ref="consoleLog"/>
        <appender-ref ref="fileInfoLog"/>
        <appender-ref ref="fileErrorLog"/>
    </root>
</configuration>

Another example is if the particle size finer then, depending on the module, the output to a different file, the configuration may be as follows

 <!--特殊功能单独appender 例如调度类的日志-->
    <appender name="CLASS-APPENDER" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>INFO</level>
        </filter>
        <encoder>
            <pattern>
                %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{50} - %msg%n
            </pattern>
        </encoder>
        <!--滚动策略-->
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!--路径-->
            <fileNamePattern>${logging.path}/mkc.class.%d{yyyy-MM-dd}.log</fileNamePattern>
            <MaxHistory>90</MaxHistory>
        </rollingPolicy>
    </appender>
    <!--这里的name和业务类中的getLogger中的字符串是一样的-->
    <logger name="xiaoming" level="INFO" additivity="true">
        <appender-ref ref="CLASS-APPENDER" />
    </logger>

Under normal circumstances xiaoming means of

private Logger xiaoming = LoggerFactory.getLogger("xiaoming");

If we use the lomok plug-in, xiaoming refers to the topic

@Slf4j(topic = "xiaoming")
public class XiaoMingTest {

}

other

Xiao Ming is currently used so much more attractive, more logging configuration scenarios, you can access: read this configuration will not logback, you eat melon!

Have any questions, welcome to leave a message -
welcome attention to the micro-channel public number "programmer Xiao Ming", for more resources.

Guess you like

Origin www.cnblogs.com/coderxx/p/11390341.html