logback console print information

1) logback log component

Introduction: logback is an open source log component, which belongs to the upgraded version of Log4j, and is now used more and more by the project team.

advantage:

1. Initial loading memory is small

2. When the configuration is modified, the configuration file is automatically reloaded, and the scanning process is fast and safe

Constituent modules: logback-core, logback-classic, logback-access

logback-core provides the core functions of logback and is the basis of the other two components;

The logback-classic module implements the SLF4J API;

The logback-access module is integrated with the Servlet container to provide Http to access logs.

How to use: import jar in pom.xml in maven

<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-core</artifactId>
    <version>1.1.11</version>
</dependency>
	
<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>1.1.11</version>
</dependency>
	
<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-access</artifactId>
    <version>1.1.11</version>
</dependency>
 
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.25</version>
</dependency>

Logback log scanning order: (logback supports two configuration methods with the suffix name being groovy and xml)

Step 1: First check whether there is a value corresponding to logback.configurationFile in the System Property system configuration file

Step 2: Find if there is a logback.groovy file in the classpath

Step 3: Find if there is a logback-test.xml file in the classpath

Step 4: Find if there is a logback.xml file in the classpath

The above 4 steps only need to conform to one of the logics. The specific code implementation can be seen in the findURLOfDefaultConfigurationFile method of the ch.qos.logback.classic.util.ContextInitializer class.

If the above 4 steps are met, logback will construct a console output log by default, and there will be a default log format.

Initialization method:

The first one: initialize by specifying the name

private final static Logger LOGGER = LoggerFactory.getLogger(“HelloLogback”);

The second method: initialized by Class

private final static Logger LOGGER = LoggerFactory.getLogger(HelloLogback.class);
package com.oysept.logback;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HelloLogback {

private final static Logger LOGGER = LoggerFactory.getLogger(HelloLogback.class);

public static void main(String[] args) {
    LOGGER.debug("this is debug message");
    LOGGER.info("this is info message");
    LOGGER.warn("this is warning message");
    LOGGER.error("this is error message");
    LOGGER.warn("this is  login message");
}

}
2) Logback log console output
Add console output log configuration in logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<!-- 自定义属性 -->
<property name="pattern" value="%X{thread} [%date{yyyy-MM-dd HH:mm:ss.SSS}] %level %logger{36} %line - %msg%n"/>

<!--控制台输出 -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
        <!-- 设置日志输出格式 -->
        <pattern>${pattern}</pattern>
		
        <!-- 设置输出字符集编码 -->
        <charset>UTF-8</charset>
    </encoder>
</appender>

<!-- 根root looger -->
<root level="DEBUG">
    <appender-ref ref="STDOUT" />
</root>
Detailed explanation of logback.xml configuration file

1. Configuration: configure the root node

2. property: attribute variable 3. appender: destination of log output ${pattern}
    <!-- 设置输出字符集编码 -->
    <charset>UTF-8</charset>
</encoder>
4. root: root log object 3) logback log disk file output

Add disk output log configuration in logback.xml (this method is less used)

<?xml version="1.0" encoding="UTF-8" ?>
<!-- 自定义变量 -->
<property name="appName" value="ouyangjun-logback" />

<!-- 日志文件名称, 可随便命名 -->
<property name="baseFile" value="ouyangjun-logback" />

<!-- 项目所在盘符的根目录下, 也可以指定具体盘符位置, 如:E:\\app\\ouyangjun-logback\\logs -->
<property name="rootPath" value="/app/ouyangjun-logback/logs" />

<!-- 日志输出格式 -->
<property name="pattern" value="%X{thread} [%date{yyyy-MM-dd HH:mm:ss.SSS}] %level %logger{36} %line - %msg%n"/>

<!-- 设置上下文名称 -->
<contextName>${appName}</contextName>

<!-- 磁盘文件输出日志 -->
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
    <File>${rootPath}/${baseFile}.log</File>
    <append>true</append>  
    <prudent>false</prudent>
	
    <!-- 日志输出格式 -->
    <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
        <pattern>${pattern}</pattern>
        
        <!-- 设置字符集 -->
        <charset>UTF-8</charset>
    </encoder>
</appender>

<root level="INFO">
    <appender-ref ref="FILE" />
</root>
4) logback log rolling output (disk)

Add the disk output log configuration in logback.xml. When the settings take effect, log files will be generated according to the specific settings. For example, when the log file exceeds a certain size, a new log file is regenerated for storage.

Optimization point: Since every time the log is output to the disk, the IO stream operation will be performed, so the function can be realized by combining the asynchronous output log. When the log reaches a certain amount, it will be written to the disk file again.

<?xml version="1.0" encoding="UTF-8" ?>
<!-- 自定义变量 -->
<property name="appName" value="ouyangjun-logback" />

<!-- 日志文件名称, 可随便命名 -->
<property name="baseFile" value="ouyangjun-logback" />

<!-- 项目所在盘符的根目录下, 也可以指定具体盘符位置, 如:E:\\app\\ouyangjun-logback\\logs -->
<property name="rootPath" value="/app/ouyangjun-logback/logs" />

<!-- 日志输出格式 -->
<property name="pattern" value="%X{thread} [%date{yyyy-MM-dd HH:mm:ss.SSS}] %level %logger{36} %line - %msg%n"/>

<!-- 设置上下文名称 -->
<contextName>${appName}</contextName>

<!-- 磁盘文件滚动输出日志 -->
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <File>${rootPath}/${baseFile}.log</File>
    <append>true</append>  
    <prudent>false</prudent>
	
    <!-- 磁盘日志文件rolling策略 -->
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        <FileNamePattern>${rootPath}/${baseFile}_%d{yyyy-MM-dd}.log.gz</FileNamePattern>
        
        <!-- 日志在磁盘上保留天数 -->
        <maxHistory>30</maxHistory>
    </rollingPolicy>

    <!-- 日志输出格式 -->
    <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
        <pattern>${pattern}</pattern>
        
        <!-- 设置字符集 -->
        <charset>UTF-8</charset>
    </encoder>
</appender>

<!-- 把日志异步输出到磁盘文件中,避免每次都进行磁盘IO操作 -->
<appender name="ASYNC" class="ch.qos.logback.classic.AsyncAppender">
    <discardingThreshold>0</discardingThreshold>
    <queueSize>10000</queueSize>
    <appender-ref ref="FILE" />
</appender>

<root level="INFO">
    <!-- <appender-ref ref="FILE" /> -->
    
    <appender-ref ref="ASYNC" />
</root>
Asynchronously output logs to disk files to avoid disk IO operations every time 0 10000

Detailed explanation of log rollingPolicy rolling policy

The first method: formulate a log file rolling strategy based on time, such as: generate log files by day, hour, and minute

ch.qos.logback.core.rolling.TimeBasedRollingPolicy

${rootPath}/${baseFile}_%d{yyyy-MM-dd}.log.gz
<!-- 日志在磁盘上保留天数 -->
<maxHistory>30</maxHistory>
The second type: indicates that if the size of the log file exceeds the specified range, it will be split into multiple files according to the file name;

ch.qos.logback.core.rolling.FixedWindowRollingPolicy

${baseFile}_.%i.log.gz
1
3

The third type: triggeringPolicy, which is the same level as rollingPolicy, means that according to the size of the log file, the log will be triggered if it exceeds the specified size scroll;

ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy

5MB

5) logback.xml configuration file in actual combat

<?xml version="1.0" encoding="UTF-8" ?>
<!-- 自定义变量 -->
<property name="appName" value="ouyangjun-logback" />

<!-- 日志文件名称, 可随便命名 -->
<property name="baseFile" value="ouyangjun-logback" />

<!-- 项目所在盘符的根目录下, 也可以指定具体盘符位置, 如:E:\\app\\ouyangjun-logback\\logs -->
<property name="rootPath" value="/app/ouyangjun-logback/logs" />

<!-- 日志输出格式 -->
<property name="pattern" value="%X{thread} [%date{yyyy-MM-dd HH:mm:ss.SSS}] %level %logger{36} %line - %msg%n"/>

<!-- 设置上下文名称 -->
<contextName>${appName}</contextName>

<!-- 把日志在控制台输出 -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
        <pattern>${pattern}</pattern>
        
        <!-- 设置字符集 -->
        <charset>UTF-8</charset>
    </encoder>
</appender>

<!-- 磁盘文件输出日志 -->
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <File>${rootPath}/${baseFile}.log</File>
    <append>true</append>  
    <prudent>false</prudent>
	
    <!-- 日志文件rolling策略 -->
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        <FileNamePattern>${rootPath}/${baseFile}_%d{yyyy-MM-dd}.log.gz</FileNamePattern>
        <!-- 日志保留天数 -->
        <maxHistory>30</maxHistory>
    </rollingPolicy>

    <!-- 日志输出格式 -->
    <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
        <pattern>${pattern}</pattern>
        
        <!-- 设置字符集 -->
        <charset>UTF-8</charset>
    </encoder>
</appender>

<!-- 文件输出日志 (文件大小策略进行文件输出,每小时产生一个日志文件给异常监控平台进行分析) -->
<appender name="ERRORFILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <File>${rootPath}/${baseFile}_error.log</File>
    <append>true</append>  
    <prudent>false</prudent>
	
    <!-- 日志文件rolling策略 -->
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        <FileNamePattern>${rootPath}/${baseFile}_error_%d{yyyy-MM-dd}.log.gz</FileNamePattern>
        
        <!-- 日志在磁盘上保留天数 -->
        <maxHistory>30</maxHistory>
    </rollingPolicy>
    
    <!-- 过滤器,只ACCEPT接收ERROR级别的日志,其它日志级别都DENY拒绝 -->
    <filter class="ch.qos.logback.classic.filter.LevelFilter">
        <level>ERROR</level>
        <onMatch>ACCEPT</onMatch>
        <onMismatch>DENY</onMismatch>
    </filter>
    
    <!-- 日志输出格式 -->
    <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
        <pattern>${pattern}</pattern>
        
        <!-- 设置字符集 -->
        <charset>UTF-8</charset>
    </encoder>
</appender>

<!-- 把日志异步输出到磁盘文件中,避免每次都进行磁盘IO操作 -->
<appender name="ASYNC" class="ch.qos.logback.classic.AsyncAppender">
    <discardingThreshold>0</discardingThreshold>
    <queueSize>10000</queueSize>
    <appender-ref ref="FILE" />
</appender>

<root level="INFO">
    <!-- 生产环境,可以不需要再控制台输出日志 -->
    <appender-ref ref="STDOUT" />
    
    <!-- 异步输出日志到磁盘文件中 -->
    <appender-ref ref="ASYNC" />
    
    <!-- 错误文件,需要实时输出到磁盘中 -->
    <appender-ref ref="ERRORFILE" />
</root>

Guess you like

Origin blog.csdn.net/qq_34690003/article/details/130922383