Article directory
-
- logback overview
- log level (five)
- related components
- Logback configuration file (XML)
- RootLogger settings
- Appender
- Filter
- Asynchronous log configuration
- Custom Logger
- Simple use of logback (no configuration files)
- Using logback with configuration files
- log4j.properties to logback.xml
- Logback's access module
- Know the access module
- Use the access module
- Summarize
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 OFF
and ALL
are 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)
logback
The 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
( Maven
item placed resource
below)
<?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 getvalue
the 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"/>
Appender
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");
}
}
}
FileAppender (custom format and HTML)
Purpose : Log output to a file.
For FileAppender
which append = true
(appendable), FileSize bufferSize = new FileSize(8192);
(buffer size).
- Contained in the FileAppender class itself
setFile()
, and its parent classOutputStreamAppender
containssetEncoder
.
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>
- 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 (
LayoutWrappingEncoder
include Layout asHTMLLayout
)
<!-- 配置路径以及日志格式 -->
<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>
- 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.LayoutWrappingEncoder
Containslayout
the settable counterpart inhtmllayout
.
RollingFileAppender
Purpose : To create files at regular intervals and cut them according to file size.
RollingFileAppender
The class is implemented FileAppender
, that is, it has FileAppender
settable 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
fileNamePattern
to determine the name of the split file and the time of splitting (splitting the abovefile
file), andmaxFileSize
the size of a single file can be set, the maximum here is1MB
.
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");
}
}
}
Filter
Purpose : To filter the log records of the specified log level.
Filter
Can be set in any appender
, as follows:
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 error
output log levels to a file.
logback.xml
The 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");
}
}
}
Principle analysis
The above configuration is LevelFilter
a class, let's look at the attributes contained in this class:
- You can see
LevelFilter
that the class containslevel
properties andset
methods.
LevelFilter
The parent classAbstractMatcherFilter
containsonMatch
,onMismatch
properties andset
methods.
You can see that the default value FilterReply.NEUTRAL
corresponds to the enumeration class, let's look at the enumeration class again:
- 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 FileAppender
use asynchronous logging, logback.xml
the 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");
}
}
}
Description : Usually, asynchronous logs are used in high concurrency situations!
A Preliminary Study of the Source Code
The asynchronous effect is achieved by using appender
the AsyncAppender
reference defined in the configuration file . First, look at the inheritance relationship:appender
AsyncAppender
AsyncAppender
The class contains a configuration property:
AsyncAppender
The parent class AsyncAppenderBase
contains configuration properties:
- 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 BlockingQueue
the interface, that is, the queue, which has multiple implementation classes:
In AsyncAppenderBase
the method, the implementation class start()
is obtained by default :ArrayBlockingQueue
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 inheritRootLogger
.
Simple use of logback (no configuration files)
First introduce dependencies slf4j-api
(to facilitate unified API), and then introduce logback-classic
modules:
<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>
- In fact, the dependencies
slf4j-classic
are included , but the dependencies are introduced separatelyslf4j-api
for 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)API
slf4j-api
slf4j-api
slf4j-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");
}
}
The log level defaults to debug
.
Using logback with configuration files
Newly logback.xml
placed in resource
the 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
root
log level isALL
,appender
the reference isconsoleappender
,appender
the 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");
}
}
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 log4j
now 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.propertoes
to the specified input field:
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>
pattern
Note: The only thing to pay attention to is the format set in it , logback
which is not available in , so we can modify %l
the 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.63
is used in (10.0.2 does not work), youTomcat
can go toTomcat
the official website to download it.
When we start tomcat
and visit localhost:8080
the page under the URL, logs
a log file will be created in the directory when we click to visit several pages:
actual module
logback
usedaccess
The first step : copy logback-access.jar
and logback-core.jar
to $TOMCAT_HOME/lib/
the directory.
That is, place two jar packages (both version 1.17) in the directory tomcat
of the decompression directorylib
- 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.xml
in the modificationHost
value
<Valve className="ch.qos.logback.access.tomcat.LogbackValve" />
Step 3 : Copy the prepared ones logback-access.xml
to $TOMCAT_HOME/conf/
the directory
logback-access.xml
The 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
pattern
the 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 logs
generated in access.log
:
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