In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article is about what logback is in the java log. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
I. introduction of logback
Logback is another open source logging component designed by the founder of log4j, the official website: http://logback.qos.ch. It is currently divided into the following next modules:
Logback-core: the basic module of the other two modules
Logback-classic: it is an improved version of log4j, and it fully implements slf4j API so that you can easily replace it with other logging systems such as log4j or JDK14 Logging
Logback-access: the access module integrates with the Servlet container to provide access to logs through Http
Second, the reasons why logback replaces log4j:
1. Faster implementation: Logback's kernel has been rewritten to improve performance on some critical execution paths by more than 10 times. And logback not only has improved performance, but also has smaller initialization memory loads.
2. Very adequate testing: Logback has been tested for several years and countless hours. The testing of Logback is at a completely different level.
3. Logback-classic naturally implements SLF4j:Logback-classic and SLF4j. In using SLF4j, you can't even feel logback-classic. And because logback-classic implements slf4j very naturally, it's very easy to switch to log4j or something else, just provide OK as another jar package, and you don't need to move the code implemented through SLF4JAPI at all.
4. Very full documentation the official website has more than 200 pages of documents.
5, automatically reload the configuration file, when the configuration file is modified, Logback-classic can automatically reload the configuration file. The scanning process is fast and safe, and it does not need to create another scanning thread. This technology fully ensures that applications can run happily in the JEE environment.
6. Lilith is the observer of log events, similar to log4j's chainsaw. Lilith can also handle large amounts of log data.
7. Cautious mode and very friendly recovery. In prudent mode, multiple FileAppender instances running under multiple JVM can safely write the same log file. There will be some restrictions on RollingFileAppender. Logback's FileAppender and its subclasses, including RollingFileAppender, are very amicable to recover from the Icano exception.
8. Configuration files can handle different situations, and developers often need to judge different Logback configuration files in different environments (development, testing, production). These profiles are only slightly different and can be implemented through, and, so that one profile can be adapted to multiple environments.
9. Filters (filter) sometimes, you need to diagnose a problem and log it. In log4j, you can only lower the log level, but this will result in a large number of logs and affect the performance of the application. In Logback, you can continue to maintain that log level and remove some special cases, such as alice login, her log will be at the DEBUG level and other users can continue to call at the WARN level. To achieve this function, you only need to add 4 lines of XML configuration. Please refer to MDCFIlter.
10. SiftingAppender (a very versatile Appender): it can be used to split log files according to any given running parameter. For example, SiftingAppender can distinguish between log events that follow a user's Session, and then each user will have a log file.
11. Automatically compress the typed log:RollingFileAppender automatically compress the typed log file when it generates a new file. Compression is an asynchronous process, so even for large log files, the application during compression will not be affected in any way.
12. Stack tree with package version: Logback will bring the package data when typing out the stack tree log.
13. Automatically remove old log files: by setting the maxHistory property of TimeBasedRollingPolicy or SizeAndTimeBasedFNATP, you can control the maximum number of log files that have been generated. If you set maxHistory 12, those log files that are longer than 12 months will be automatically removed.
Introduction to the configuration of logback
1. Logger, appender and layout
Logger as a log recorder, after associating it to the corresponding context of the application, it is mainly used to store log objects, and can also define log types and levels.
Appender is primarily used to specify the destination of log output, which can be console, file, remote socket server, MySQL, PostreSQL, Oracle, and other databases, JMS, and remote UNIX Syslog daemons, and so on.
Layout is responsible for converting events into strings and formatting the output of log information.
2 、 logger context
Each logger is associated with a LoggerContext,LoggerContext responsible for manufacturing the logger and arranging the logger in a tree structure. All other logger is also obtained through the static method getLogger of the org.slf4j.LoggerFactory class. The getLogger method takes the logger name as an argument. Calling the LoggerFactory.getLogger method with the same name always results in a reference to the same logger object.
3. Effective level and inheritance of level
Logger can be assigned a level. The levels include: TRACE, DEBUG, INFO, WARN, and ERROR, defined in the ch.qos.logback.classic.Level class. If the logger is not assigned a level, it inherits the level from the nearest ancestor who has the assigned level. The default level of root logger is DEBUG.
4. Printing method and basic selection rules
The printing method determines the level of the recording request. For example, if L is an instance of logger, the statement L.info ("..") Is a record statement at the level of INFO. The level of the record request is said to be enabled when it is higher than or equal to the valid level of its logger; otherwise, it is called disabled. The record request level is p, its logger valid level is Q, and the request will be executed only if p > = Q.
This rule is the core of logback. The order of the level is: TRACE
< DEBUG < INFO < WARN < ERROR 四、logback的默认配置 如果配置文件 logback-test.xml 和 logback.xml 都不存在,那么 logback 默认地会调用BasicConfigurator ,创建一个最小化配置。最小化配置由一个关联到根 logger 的ConsoleAppender 组成。输出用模式为%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n 的 PatternLayoutEncoder 进行格式化。root logger 默认级别是 DEBUG。 1、Logback的配置文件 Logback 配置文件的语法非常灵活。正因为灵活,所以无法用 DTD 或 XML schema 进行定义。尽管如此,可以这样描述配置文件的基本结构:以开头,后面有零个或多个元素,有零个或多个元素,有最多一个元素。 2、Logback默认配置的步骤 (1). 尝试在 classpath下查找文件logback-test.xml; (2). 如果文件不存在,则查找文件logback.xml; (3). 如果两个文件都不存在,logback用BasicConfigurator自动对自己进行配置,这会导致记录输出到控制台。 五、logback.xml常用配置详解 1、根节点,包含下面三个属性: scan: 当此属性设置为true时,配置文件如果发生改变,将会被重新加载,默认值为true。 scanPeriod: 设置监测配置文件是否有修改的时间间隔,如果没有给出时间单位,默认单位是毫秒。当scan为true时,此属性生效。默认的时间间隔为1分钟。 debug: 当此属性设置为true时,将打印出logback内部日志信息,实时查看logback运行状态。默认值为false。 例如: 2、子节点:用来设置上下文名称,每个logger都关联到logger上下文,默认上下文名称为default。但可以使用设置成其他名字,用于区分不同应用程序的记录。一旦设置,不能修改。 例如: myAppName 3、子节点 :用来定义变量值,它有两个属性name和value,通过定义的值会被插入到logger上下文中,可以使"${}"来使用变量。 name: 变量的名称 value: 的值时变量定义的值 例如: ${APP_Name} 4、子节点:获取时间戳字符串,他有两个属性key和datePattern key: 标识此 的名字; datePattern: 设置将当前时间(解析配置文件的时间)转换为字符串的模式,遵循java.txt.SimpleDateFormat的格式。 例如: ${bySecond} 5、子节点:负责写日志的组件,它有两个必要属性name和class。name指定appender名称,class指定appender的全限定名 5.1、ConsoleAppender 把日志输出到控制台,有以下子节点: :对日志进行格式化。(具体参数稍后讲解 ) :字符串System.out(默认)或者System.err(区别不多说了) 例如: %-4relative [%thread] %-5level %logger{35} - %msg %n 上述配置表示把>= DEBUG-level logs are output to the console
5.2. FileAppender: add the log to the file with the following child nodes:
The file name to be written can be either a relative directory or an absolute directory. It will be created automatically if the parent directory does not exist, and there is no default value.
If it is true, the log is appended to the end of the file. If it is false, empty the existing file. Default is true.
Format logged events (specific parameters will be explained later)
If it is true, the log will be safely written to the file, even if other FileAppender are also writing to this file, which is inefficient. The default is false.
For example:
TestFile.log
True
%-4relative [% thread]%-5level% logger {35} -% msg%n
The above configuration means that all logs at the > = DEBUG level are output to testFile.log.
RollingFileAppender: scroll to record the file, first record the log to the specified file, and then log to other files when certain conditions are met. There are the following child nodes:
The file name to be written can be either a relative directory or an absolute directory. It will be created automatically if the parent directory does not exist, and there is no default value.
If it is true, the log is appended to the end of the file. If it is false, empty the existing file. Default is true.
When scrolling occurs, determines the behavior of RollingFileAppender, which involves file movement and renaming The property class defines a specific scrolling policy class
Class= "ch.qos.logback.core.rolling.TimeBasedRollingPolicy": the most commonly used scrolling strategy, which formulates the scrolling strategy based on time, and is responsible for both scrolling and starting scrolling. There are the following child nodes:
: necessary node, including file name and "% d" conversion character, "% d" can contain a time format specified by java.text.SimpleDateFormat, such as:% d {yyyy-MM}.
If you use d directly, the default format is yyyy-MM-dd. The file node of RollingFileAppender is optional. By setting file, you can specify different locations for active files and archived files. The current log is always recorded to the file specified by file (active file), and the name of the active file will not be changed.
If file is not set, the name of the active file will be changed at regular intervals based on the value of fileNamePattern. "/" or "\" will be used as directory delimiters.
:
An optional node that controls the maximum number of archive files retained, and deletes old files when the number is exceeded. If you set scrolling every month, and it is 6, only the files for the last 6 months are saved, and the previous files are deleted. Note that if you delete old files, directories created for archiving will also be deleted.
Class= "ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy": check the size of the currently active file. If the size exceeds the specified size, it will tell RollingFileAppender to trigger the currently active file scrolling. There is only one node:
This is the size of the active file, and the default value is 10MB.
When true, FixedWindowRollingPolicy is not supported TimeBasedRollingPolicy is supported, but there are two restrictions: 1 does not support or allow file compression, and 2 cannot set the file attribute and must be left blank.
Inform RollingFileAppender that scrolling is appropriate.
Class= "ch.qos.logback.core.rolling.FixedWindowRollingPolicy" renames the scrolling strategy of the file according to the fixed window algorithm. There are the following child nodes:
Window index minimum
The maximum value of the window index, which is automatically set to 12 when the window specified by the user is too large
Must include "% I" for example, assuming that the minimum and maximum values are 1 and 2, respectively, and the naming pattern is mylog%i.log, the archive files mylog1.log and mylog2.log will be generated. You can also specify file compression options, such as mylog%i.log.gz or no log%i.log.zip
For example:
LogFile.%d {yyyy-MM-dd} .log
thirty
%-4relative [% thread]%-5level% logger {35} -% msg%n
The above configuration means that a log file is generated every day and the log file is saved for 30 days.
Test.log
Tests.%i.log.zip
one
three
5MB
%-4relative [% thread]%-5level% logger {35} -% msg%n
The above configuration means that the log file is generated according to the fixed window mode, and when the file is larger than 20MB, a new log file is generated. The window size is 1 to 3, and when three archive files are saved, the oldest log is overwritten.
Format logged events Responsible for two things, one is to convert the log information into a byte array, and the other is to write the byte array to the output stream.
PatternLayoutEncoder is the only useful and default encoder, with a node that sets the input format for the log. Using "%" plus "conversion character", if you want to output "%", you must escape "\%" with "\".
SocketAppender, SMTPAppender, DBAppender, SyslogAppender, SiftingAppender, which are not commonly used, will not be explained in detail here.
You can refer to the official documentation (http://logback.qos.ch/documentation.html) and write your own Appender.
6. Child node: used to set the log printing level of a package or a specific class, as well as the assignment. There is only one name attribute, one optional level, and one optional addtivity attribute.
Can contain zero or more elements, indicating that the appender will be added to the loger
Name: used to specify a package or a specific class that is constrained by this loger.
Level: used to set the print level, case-independent: TRACE, DEBUG, INFO, WARN, ERROR, ALL and OFF, as well as a vulgar value INHERITED or synonym NULL, which represents the level at which the parent is enforced. If this property is not set, the current loger will inherit the level of the parent.
Addtivity: whether to transfer print information to the superior loger. The default is true. As such, it can contain zero or more elements, indicating that the appender will be added to the loger.
7. Child node: it is also an element, but it is the root loger, the parent of all. There is only one level attribute because name has been named "root" and is already the highest level.
Level: used to set the print level, case-independent: TRACE, DEBUG, INFO, WARN, ERROR, ALL and OFF, cannot be set to INHERITED or synonym NULL. The default is DEBUG.
VI. Common loger configurations
7. Demo
1. Adding dependency packages logback needs to be used together with slf4j, so the total package that needs to add dependencies is slf4j-api
Logback needs to be used with slf4j, so the packages that need to add dependencies are slf4j-api.jar,logback-core.jar,logback-classic.jar,logback-access.jar, which is not available temporarily, so do not add dependencies, maven configuration
UTF-8
1.1.7
1.7.21
Org.slf4j
Slf4j-api
${slf4j.version}
Compile
Ch.qos.logback
Logback-core
${logback.version}
Ch.qos.logback
Logback-classic
${logback.version}
2. Logback.xml configuration
% d {yyyy-MM-dd HH:mm:ss.SSS} [% thread]%-5level% logger {50} -% msg%n
${LOG_HOME} / TestWeb.log.%d {yyyy-MM-dd} .log
thirty
% d {yyyy-MM-dd HH:mm:ss.SSS} [% thread]%-5level% logger {50} -% msg%n
10MB
3. Java code
/ * *
* Hello world!
* /
Public class App {
Private final static Logger logger = LoggerFactory.getLogger (App.class)
Public static void main (String [] args) {
Logger.info ("logback succeeded")
Logger.error ("logback succeeded")
Logger.debug ("logback succeeded")
}
}
Thank you for reading! This is the end of the article on "what is logback in the java log". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.