Java logging framework logback


Original link: https://changlu.blog.csdn.net/article/details/114860566

logback overview

Official website: https://logback.qos.ch/index.html
Logback: It is also an open source log component designed by the founder of log4j after leaving Apache, and its performance is better than Log4j.
logback is divided into three modules: logback-core, logback-classic and logback-access
logback-core: lays the foundation for the other two modules
logback-classic: it is an improved version of log4j, and it fully implements the slf4j API.
logback-access: The access module is integrated with the Servlet container to provide the function of accessing logs through Http.
Nowadays, the log frameworks use the slf4j log facade to build the log system. Most of the log implementation frameworks include the slf4j-api dependency, and then mainly modify the configuration file and pom.xml.

log level (five)

package ch.qos.logback.classic;

public final class Level implements Serializable {
    
    

    public static final Level OFF = new Level(2147483647, "OFF");
    public static final Level ERROR = new Level(40000, "ERROR");
    public static final Level WARN = new Level(30000, "WARN");
    public static final Level INFO = new Level(20000, "INFO");
    public static final Level DEBUG = new Level(10000, "DEBUG");
    public static final Level TRACE = new Level(5000, "TRACE");
    public static final Level ALL = new Level(-2147483648, "ALL");
	...
}

Log levels are sorted as: TRACE< DEBUG< INFO< WARN< ERROR. The default log level is Debug, where OFFand ALLare used as log switches.

related components

Logback also contains three components, Logger, Appender, and Layout, which are similar to Log4j:
Logger: Logger, after associating it with the corresponding context of the application, is mainly used to store log objects, and can also define log types and levels .
Appender: used to specify the destination of the log output, the destination can be console, file, database, etc.
Layout: Responsible for converting events into strings and outputting formatted log information. In Logback, the Layout object is encapsulated in the encoder.

Logback configuration file (XML)

logbackThe following types of configuration files are read by default when using the logging framework:

  • logback.groovy
  • logback-test.xml
  • logback.xml

If none exist, the default configuration will be used, the log level is DEBUG, and the default output is to console.

General creation logback.xml( Mavenitem placed resourcebelow)

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
	<!--....相关配置信息-->
</configuration>

RootLogger settings

root basic settings

<!--  设置root的日志等级为ALL  -->
<root level="ALL">
    <!--  指定appender引用,这里例如引用下面的appender  -->
    <appender-ref ref="console"/>
</root>

Configure key-value pairs and obtain the value of the corresponding key

<!-- ①配置一对键值对,其name可被引用-->
<property name="pattern"  value="%-5level %d{yyyy-MM-dd HH:mm:ss.SSS} %c %M %L [%thread] %m%n"/>

<!--  配置appender过程中引用对应键值对  -->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
    <!--   设置自定义格式布局   -->
    <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
        <!--  ********************  -->
        <!--   ②注意这里使用${name}包裹能够引用property中name对应的value   -->
        <pattern>${pattern}</pattern>
        <!--  ********************  -->
    </encoder>
</appender>

  • Pay attention to ①②, refer to the pre-configured one in ② property, and use it ${}to get valuethe value

log output format

<!--
    日志输出格式:
    %-5level:日志等级
    %d{yyyy-MM-dd HH:mm:ss.SSS}:日期
    %c:类的完整名称
    %M:method
    %L:行号
    %thread:线程名称
    %m或者%msg:信息
    %n:换行
-->
<!--配置一对键值对  日志等级(值为靠左对齐5个位子) 日期 类完整名 方法 行号 线程名 信息及换行-->
<property name="pattern"  value="%-5level %d{yyyy-MM-dd HH:mm:ss.SSS} %c %M %L [%thread] %m%n"/>

image-20210308233746000

Appender

image-20210309230921208

  • ConsoleAppender: output to the screen.
  • FileAppender: Output to the specified file.
    • RollingFileAppender: Create files at regular intervals and cut them according to file size.

ConsoleAppender

Purpose : output to the screen.

Configuration logback.xml:

Example demonstration


<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <!--  可见root基本设置中的格式介绍  -->
    <property name="pattern"  value="%-5level %d{yyyy-MM-dd HH:mm:ss.SSS} %c %M %L [%thread] %m%n"/>

    <!--  ********************  -->
    <!--  配置ConsoleAppender  -->
    <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
        <!--  输出流对象  -->
        <target>System.err</target>
        <!--   日志格式配置   -->
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <!--   设置输出格式引用上面的键值对及输出的格式   -->
            <pattern>${pattern}</pattern>
        </encoder>
    </appender>
  
    <!-- 设置root,引用appender  -->
    <root level="ALL">
        <appender-ref ref="console"/>
        <appender-ref ref="file"/>
    </root>
</configuration>


Run the program :

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

public class LogTest {
    
    
    //获取Logger实例
    public static final Logger LOGGER = LoggerFactory.getLogger(LogTest.class);

    public static void main(String[] args) {
    
    
        //为了效果明显循环10000次
        for (int i = 0; i < 10000; i++) {
    
    
            LOGGER.error("error");
            LOGGER.warn("warn");
            LOGGER.info("info");
            LOGGER.debug("debug");
            LOGGER.trace("trace");
        } 
    }
}

image-20210309220018552

FileAppender (custom format and HTML)

Purpose : Log output to a file.

For FileAppenderwhich append = true(appendable), FileSize bufferSize = new FileSize(8192);(buffer size).

image-20210309233151621

  • Contained in the FileAppender class itself setFile(), and its parent class OutputStreamAppendercontains setEncoder.

Output to a file whose format is a custom format ( PatternLayoutEncoder)


<!-- 配置路径以及日志格式  -->
<property name="log_dir"  value="d:/logs"/>
<property name="pattern"  value="%-5level %d{yyyy-MM-dd HH:mm:ss.SSS} %c %M %L [%thread] %m%n"/>

<!--  ********************  -->
<!--  配置fileAppender  -->
<appender name="file" class="ch.qos.logback.core.FileAppender">
    <!--  配置文件路径  -->
    <file>${log_dir}/logback.log</file>
    <!--  日志格式设置  -->
    <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
        <pattern>${pattern}</pattern>
    </encoder>
</appender>
<!--  ********************  -->

<!--  设置root的日志等级为ALL,以及引用上面的name为console的appender  -->
<root level="ALL">
    <!--  这里console只用来表示root标签可设置多个appender,无引用上面的意思 -->
    <appender-ref ref="console"/>
    <appender-ref ref="file"/>
</root>

image-20210309223615545

  • The output program can be seen in 3.2 below, and the corresponding key-value pair setting is nothing more than the related set method of the corresponding specified class or its parent class, which can be seen in the source code.

The format of the output to the file is HTML format ( LayoutWrappingEncoderinclude Layout as HTMLLayout)

<!-- 配置路径以及日志格式  -->
<property name="log_dir"  value="d:/logs"/>
<property name="pattern"  value="%-5level %d{yyyy-MM-dd HH:mm:ss.SSS} %c %M %L [%thread] %m%n"/>

<!--  ********************  -->
<!--  配置HTML格式的Appender  -->
<appender name="htmlFile" class="ch.qos.logback.core.FileAppender">
    <!--  配置文件路径  -->
    <file>${log_dir}/logback.html</file>
    <!--  日志格式设置  -->
    <encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
        <!--  设置了HTMLLayout的layout  -->
        <layout class="ch.qos.logback.classic.html.HTMLLayout">
            <!--  注意:输出格式为HTML时,不需要有空格或者其他符号或者换行,否则输出格式会有空格不美观  -->
            <pattern>%-5level%d{yyyy-MM-dd HH:mm:ss.SSS}%c%M%L%thread%m</pattern>
        </layout>
    </encoder>
</appender>
<!--  ********************  -->

<!--  设置root的日志等级为ALL,引用console和  -->
<root level="ALL">
    <!--  这里console只用来表示root标签可设置多个appender,无引用上面的意思 -->
    <appender-ref ref="console"/>
    <appender-ref ref="htmlFile"/>
</root>

image-20210309224144946

  • See 3.2 for the test procedure, and the corresponding label setting is nothing more than the corresponding set method.
  • ch.qos.logback.core.encoder.LayoutWrappingEncoderContains layoutthe settable counterpart in htmllayout.

RollingFileAppender

Purpose : To create files at regular intervals and cut them according to file size.

RollingFileAppenderThe class is implemented FileAppender, that is, it has FileAppendersettable attribute content such as Encoder, file(output path)

<!--  设置路径键值对 -->
<property name="log_dir"  value="d:/logs"/>

<!--  ********************  -->
<!--  日志拆分和归档的appender对象 -->
<appender name="rollingFile" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <!--  配置文件路径  -->
    <file>${log_dir}/roll_logback.log</file>
    <!--  自定义日志格式设置  -->
    <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
        <pattern>${pattern}</pattern>
    </encoder>
    <!--   指定日志文件拆分与压缩规则     -->
    <RollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
        <!--   通过指定压缩文件名称来确定分割文件方式,这里是设置为年月日  
   			可精确到毫秒:%d{yyyy-MM-dd-hh-mm-ss-SSS}
		-->
        <fileNamePattern>${log_dir}/rolling.%d{yyyy-MM-dd-hh-mm-ss}.log%i.gz</fileNamePattern>
        <!--   文件拆分大小,超过1MB即拆分     -->
        <maxFileSize>1MB</maxFileSize>
    </RollingPolicy>
</appender>
<!--  ********************  -->

<!--  设置root的日志等级为ALL,引用appender  -->
<root level="ALL">
    <appender-ref ref="rollingFile"/>
</root>

  • Line 13: The set log file splitting and compression rule class, which contains two attributes fileNamePatternto determine the name of the split file and the time of splitting (splitting the above filefile), and maxFileSizethe size of a single file can be set, the maximum here is 1MB.

Test procedure :

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

public class LogTest {
    
    
    //获取Logger实例
    public static final Logger LOGGER = LoggerFactory.getLogger(LogTest.class);

    public static void main(String[] args) {
    
    
        //为了效果明显循环10000次
        for (int i = 0; i < 10000; i++) {
    
    
            LOGGER.error("error");
            LOGGER.warn("warn");
            LOGGER.info("info");
            LOGGER.debug("debug");
            LOGGER.trace("trace");
        } 
    }
}

image-20210309231919221

Filter

Purpose : To filter the log records of the specified log level.

FilterCan be set in any appender, as follows:

image-20210310152956525

  • EvaluatorFilter: Critical filter, which filters out logs below the specified threshold.
  • LevelFilter: Level filter, to filter logs of a specific level.

LevelFilter

Configuration instructions

Introduction to the three attributes of the configuration LevelFilter:

level: Set the log level for filtering.
onMatch: Perform an action when the log level is matched.
onMismatch: Perform an action when the log level does not match.
Among them, onMatch and onMismatch correspond to the specified enumeration value (three):

DENY: The log will be discarded immediately without going through other filters. (Negative meaning)
NEUTRAL: The next filter in the ordered list passes and then processes the log; (this level neither processes nor discards, which means that there is no processing, and the log will be saved and executed in this appender) ( Neutral)
ACCEPT: The log will be processed immediately without going through the remaining filters. (by meaning)

Example use

Requirement: Only erroroutput log levels to a file.

logback.xmlThe configuration is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <!--  配置fileAppender  -->
    <appender name="file" class="ch.qos.logback.core.FileAppender">
        <!--  配置文件路径  -->
        <file>${log_dir}/logback.log</file>
        <!--  日志格式设置  -->
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <pattern>${pattern}</pattern>
        </encoder>
        <!--  ********************  -->
        <!--  配置日志等级过滤器:LevelFilter  -->
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <!--  指定日志等级  -->
            <level>error</level>
            <!--  若是>=error(匹配)直接通过不过滤 -->
            <onMatch>ACCEPT</onMatch>
            <!--  若是<error(不匹配)过滤掉 -->
            <onMismatch>DENY</onMismatch>
        </filter>
        <!--  ********************  -->
    </appender>

    <!--  设置root的日志等级为ALL,以及引用上面的name为console的appender  -->
    <root level="ALL">
        <appender-ref ref="file"/>
    </root>
</configuration>

Test procedure :

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

public class LogTest {
    
    
    //获取Logger实例
    public static final Logger LOGGER = LoggerFactory.getLogger(LogTest.class);

    public static void main(String[] args) {
    
    
        for (int i = 0; i < 10000; i++) {
    
    
            LOGGER.error("error");
            LOGGER.warn("warn");
            LOGGER.info("info");
            LOGGER.debug("debug");
            LOGGER.trace("trace");
        }
    }
}

image-20210310155141378

Principle analysis

The above configuration is LevelFiltera class, let's look at the attributes contained in this class:

image-20210310214426741

  • You can see LevelFilterthat the class contains levelproperties and setmethods.

image-20210310214452764

  • LevelFilterThe parent class AbstractMatcherFiltercontains onMatch, onMismatchproperties and setmethods.

You can see that the default value FilterReply.NEUTRALcorresponds to the enumeration class, let's look at the enumeration class again:

image-20210310214645769

  • Corresponding to three examples, see above for corresponding meanings.

Asynchronous log configuration

introduce

We used synchronous logs to print logs before, but we can set up asynchronous for systems with high concurrency and low latency requirements.

Asynchronous : When printing the log, the print task is put into the memory queue and returned directly, unlike the synchronous log, which directly writes to the disk every time.

Example use

To FileAppenderuse asynchronous logging, logback.xmlthe configuration is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
	<!--  配置fileAppender  -->
    <appender name="file" class="ch.qos.logback.core.FileAppender">
        <!--  配置文件路径  -->
        <file>${log_dir}/logback.log</file>
        <!--  日志格式设置  -->
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <pattern>${pattern}</pattern>
        </encoder>
        <!--  配置日志等级过滤器:LevelFilter  -->
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <!--  指定日志等级  -->
            <level>error</level>
            <!--  若是>=error(匹配)直接通过不过滤 -->
            <onMatch>ACCEPT</onMatch>
            <!--  若是<error(不匹配)过滤掉 -->
            <onMismatch>DENY</onMismatch>
        </filter>
    </appender>

    <!--  设置异步日志 -->
    <appender name="async" class="ch.qos.logback.classic.AsyncAppender">
        <!--设为0表示队列达到80%,也不丢弃任务-->
        <discardingThreshold>0</discardingThreshold>
        <!--队列的深度,该值会影响性能,默认256,这里设置1024-->
        <queueSize>1024</queueSize>
        <!--队列满了直接丢弃要写的消息-->
        <neverBlock>true</neverBlock>
        <!--One and only one appender may be attached to AsyncAppender,添加多个的话后面的会被忽略-->
        <appender-ref ref="file"/>
    </appender>
    
    <!--  设置root的日志等级为ALL,以及引用上面的name为console的appender  -->
    <root level="ALL">
        <appender-ref ref="file"/>
    </root>
</configuration>

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

public class LogTest {
    
    
    //获取Logger实例
    public static final Logger LOGGER = LoggerFactory.getLogger(LogTest.class);

    public static void main(String[] args) {
    
    
        for (int i = 0; i < 10000; i++) {
    
    
            LOGGER.error("error");
            LOGGER.warn("warn");
            LOGGER.info("info");
            LOGGER.debug("debug");
            LOGGER.trace("trace");
        }
    }
}

image-20210310162021561

Description : Usually, asynchronous logs are used in high concurrency situations!

A Preliminary Study of the Source Code

The asynchronous effect is achieved by using appenderthe AsyncAppenderreference defined in the configuration file . First, look at the inheritance relationship:appenderAsyncAppender

image-20210310215022350

AsyncAppenderThe class contains a configuration property:

image-20210310215602838

AsyncAppenderThe parent class AsyncAppenderBasecontains configuration properties:

image-20210310215939919

  • The corresponding attributes are described as follows:
<!--可设置属性介绍-->
<!--队列的深度,该值会影响性能,默认256-->
<queueSize>512</queueSize>
<!--设为0表示队列达到80%,也不丢弃任务-->
<discardingThreshold>0</discardingThreshold>
<!--日志上下文关闭后,AsyncAppender继续执行写任务的时间,单位毫秒-->
<maxFlushTime>1000</maxFlushTime>
<!--队列满了直接丢弃要写的消息-->
<neverBlock>true</neverBlock>
<!--是否包含调用方的信息,false则无法打印类名方法名行号等-->
<includeCallerData>true</includeCallerData>
<appender-ref ref="file"/>

What needs to be known is that the attributes in the asynchronous logger include BlockingQueuethe interface, that is, the queue, which has multiple implementation classes:

image-20210310220124992

In AsyncAppenderBasethe method, the implementation class start()is obtained by default :ArrayBlockingQueue

image-20210310220202562

A lot of configuration information is actually indirectly related to this queue implementation class! ! ! Here is enough to understand for the time being, and no further exploration will be made.

Custom Logger

introduce

Purpose : It can be customized according to different business needs Logger. For example, self-defined messages can be output to the console by customizing, and system messages can be output to log files. LoggerFactory.getLogger(指定类或包名);An instance of the specified configuration can be obtained by using logger.

How to use

<!--自定义logger   additivity:表示是否从 rootLogger继承配置-->
<logger name="xyz.changlu" level="debug" additivity="false">
    <appender-ref ref="console"/>
</logger>

  • Labels are used here <logger>as custom labels.
  • additivity: Set a boolean indicating whether to inherit RootLogger.

Simple use of logback (no configuration files)

First introduce dependencies slf4j-api(to facilitate unified API), and then introduce logback-classicmodules:

<dependencies>
    <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.30</version>
</dependency>
<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>1.2.3</version>
    </dependency>
</dependencies>

image-20210308223412622

  • In fact, the dependencies slf4j-classicare included , but the dependencies are introduced separately slf4j-apifor the unified management of logs . (Think of it this way, if you don’t import a separate dependency, then changing the log framework will cause problems with the introduction of corresponding different dependencies)APIslf4j-apislf4j-apislf4j-api
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LogTest {
    
    
    //获取Logger实例
    public static final Logger LOGGER = LoggerFactory.getLogger(LogTest.class);

    public static void main(String[] args) {
    
    
        LOGGER.error("error");
        LOGGER.warn("warn");
        LOGGER.info("info");
        LOGGER.debug("debug");
        LOGGER.trace("trace");
    }
}

image-20210308223719275

The log level defaults to debug.

Using logback with configuration files

Newly logback.xmlplaced in resourcethe directory:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <!--
        日志输出格式:
        %-5level:日志等级
        %d{yyyy-MM-dd HH:mm:ss.SSS}:日期
        %c:类的完整名称
        %M:method
        %L:行号
        %thread:线程名称
        %m或者%msg:信息
        %n:换行
    -->
    <!--配置一对键值对-->
    <property name="pattern"  value="%-5level %d{yyyy-MM-dd HH:mm:ss.SSS} %c %M %L [%thread] %m%n"/>
    
    <!--  配置ConsoleAppender  -->
    <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
        <!--  输出流对象  -->
        <target>System.err</target>
        <!--   日志格式配置   -->
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <!--   引用上面的键值对及输出的格式   -->
            <pattern>${pattern}</pattern>
        </encoder>
    </appender>

    <!--  设置root的日志等级为ALL,以及引用上面的name为console的appender  -->
    <root level="ALL">
        <!--  可设置多个appender  -->
        <appender-ref ref="console"/>
    </root>

</configuration>

  • The set rootlog level is ALL, appenderthe reference is consoleappender, appenderthe output stream object and the log format configuration are set (the custom log format layout, the format is also a reference).

test program

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

public class LogTest {
    
    
    //获取Logger实例
    public static final Logger LOGGER = LoggerFactory.getLogger(LogTest.class);

    public static void main(String[] args) {
    
    
        LOGGER.error("error");
        LOGGER.warn("warn");
        LOGGER.info("info");
        LOGGER.debug("debug");
        LOGGER.trace("trace");
    }
}

image-20210308233203742

The running content is displayed to be the same as that in the configuration file, and the configuration is successful.

log4j.properties to logback.xml

For some old projects that were originally used but log4jnow want to be used logback, the corresponding configuration files must also need to be rewritten, but we also have an easy way to achieve it through the conversion function provided by the official website: logback conversion page

We just copy what we want to convert log4j.propertoesto the specified input field:

image-20210310231129271

The converted content is as follows :

log4j.properties

log4j.rootLogger = trace,file
# FileAppender
#  file为名称   其中属性file:文件路径   encoding:编码
log4j.appender.file = org.apache.log4j.FileAppender
log4j.appender.file.file = C:/Users/93997/Desktop/projectexers/logs/log.txt
log4j.appender.file.encoding = UTF-8
#  设置自定义布局(自定义输出格式)
log4j.appender.file.layout = org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern= [%-5p]%r %l %d{
    
    yyyy-MM-dd HH:mm:ss:SSS} %m%n

logback.xml

<?xml version="1.0" encoding="UTF-8"?>

<!-- For assistance related to logback-translator or configuration  -->
<!-- files in general, please contact the logback user mailing list -->
<!-- at http://www.qos.ch/mailman/listinfo/logback-user             -->
<!--                                                                -->
<!-- For professional support please see                            -->
<!--    http://www.qos.ch/shop/products/professionalSupport         -->
<!--                                                                -->
<configuration>
  <appender name="file" class="ch.qos.logback.core.FileAppender">
    <file>C:/Users/93997/Desktop/projectexers/logs/log.txt</file>
    <encoding>UTF-8</encoding>
    <encoder>
      <pattern>[%-5p]%r %l %d{yyyy-MM-dd HH:mm:ss:SSS} %m%n</pattern>
    </encoder>
  </appender>
  <root level="trace">
    <appender-ref ref="file"/>
  </root>
</configuration>

patternNote: The only thing to pay attention to is the format set in it , logbackwhich is not available in , so we can modify %lthe output format of the converted configuration file .pattern

Logback's access module

Know the access module

Introduction: The Logback-access module inherits from the Servlet container (such as Tomcat, Jetty) and provides the function of HTTP access log. We can use the logback-access module to replace the access log of tomcat.

Purpose: You can use this module when you want to manage Tomcat logs in the same way, to customize log output, etc.

Use the access module

This time the content Tomcat8.5.63is used in (10.0.2 does not work), you Tomcatcan go to Tomcatthe official website to download it.

When we start tomcatand visit localhost:8080the page under the URL, logsa log file will be created in the directory when we click to visit several pages:

image-20210310233356060

actual module logbackusedaccess

The first step : copy logback-access.jarand logback-core.jarto $TOMCAT_HOME/lib/the directory.

That is, place two jar packages (both version 1.17) in the directory tomcatof the decompression directorylib

image-20210310233636961

  • You can go to the central warehouse to download or get it from my Baidu network disk (link: https://pan.baidu.com/s/1T5CJx1vR1621TDrCRsKr9Q extraction code: njy4 )

Step 2 : Add tags to the elements $TOMCAT_HOME/conf/server.xmlin the modificationHostvalue

image-20210310234012876

<Valve className="ch.qos.logback.access.tomcat.LogbackValve" />

Step 3 : Copy the prepared ones logback-access.xmlto $TOMCAT_HOME/conf/the directory

logback-access.xmlThe content is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <!-- always a good activate OnConsoleStatusListener -->
  <!-- 设置一个监听器 -->
  <statusListener class="ch.qos.logback.core.status.OnConsoleStatusListener"/> 
    
  <!-- 添加一对键值对,LOG_DIR对应着指定路径 -->
  <property name="LOG_DIR" value="${catalina.base}/logs"/>
 
  <!-- 添加RollingFileAppender,按照天来进行分割文件 -->
  <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <!-- 输出文件路径 -->
    <file>${LOG_DIR}/access.log</file>
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
      <!-- 指定文件名称(压缩包) -->
      <fileNamePattern>access.%d{yyyy-MM-dd}.log.zip</fileNamePattern>
    </rollingPolicy>
 	
    <encoder>
      <!--  官网进行了简化使用一个名称即可代表指定格式:
			combined相当于"%h %l %u [%t] "%r" %s %b "%i{Referer}" "%i{User-Agent}" -->
      <pattern>combined</pattern>
    </encoder>
  </appender>
  
  <appender-ref ref="FILE"/>
</configuration>

  • The specified name can be seen on patternthe official website (multiple name definitions): https://logback.qos.ch/access.html#configuration

We then start tomcat, and click to visit a few pages, and then look at the files logsgenerated in access.log:

image-20210310235832590

We can also change and adjust the output format content.

Summarize

1. Logback has 5 log levels, and the default log level is debug. Components also include Logger, Appender, and Encoder (encapsulating Layout). — See Chapter 1

2. Custom configuration files usually use logback.xml, and the Appender that is often used is RollingFileAppender (adding log files on time and splitting them according to file size), and LevelFilter can set the filtering log level. —See Chapter 2 Appender, Filter

3. Asynchronous logs can be configured in logback, which greatly improves performance. —See Chapter 2 Asynchronous Log Configuration

4. Log4j.properties can be converted to logback.xml on the logback official website, but it should be noted that the format configuration character %l in log4j.properteis is invalid in logback and needs to be changed. — see part 4

5. The access module in Loback can replace the access log of the serlvet container (such as Tomcat, Jetty), and can customize the format. — see section 5

Guess you like

Origin blog.csdn.net/qq_29917503/article/details/131049106