The foolish old man walking on the clouds |
Blog garden
Home page
Bo asked
Flash memory
New essays
To subscribe to
management
Logback and logback.xml
Introduction to LogBack
Logback is another open source logging component designed by the founders of Log4j, at http://logback.qos.ch. It is currently divided into the following modules:
- Logback-core: The base module of the other two modules
- Logback-classic: It is an improved version of Log4J and fully implements the SLF4J API so that you can easily switch to other Logging systems such as Log4J or JDK14 Logging
- Logback-access: The access module integrates with the Servlet container to provide log access over Http
Logback replaces log4j.
- Faster implementation: The Logback kernel was rewritten, improving performance by more than 10 times on some critical execution paths. Not only is logBack performing better, but the initial memory load is also smaller.
- Very thorough testing: Logback has been tested for years and countless hours. Logback tests are at a completely different level.
- Logback-classic implements SLF4j quite naturally: logback-classic implements SLF4j. In SLF4j, you won’t even feel logback-classic. And because Logback-classic implements SLF4J quite naturally, it’s easy to switch to Log4j or something else, just provide it as another JAR package, and don’t bother with the code implemented via SLF4JAPI at all.
- There are over 200 pages of documentation on the official website.
- Automatically reloads the configuration file. Logback-classic automatically reloads the configuration file when the configuration file is modified. The scanning process is fast and safe, and it does not require the creation of another scanning thread. This technique ensures that applications run well in JEE environments.
- Lilith is an observer of log events, similar to Log4j’s Chainsaw. Lilith can also handle large amounts of log data.
- Cautious mode and very recovery-friendly. In cautious mode, multiple FileAppender instances running under multiple JVMS can safely write to the same log file. RollingFileAppender has some limitations. Logback’s FileAppender and its subclasses including RollingFileAppender are very friendly to recovering from I/O exceptions.
- Profiles can handle different situations, and developers often need to judge different Logback profiles in different environments (development, test, production). These profiles have only minor differences that can be implemented with, and, so that one profile can accommodate multiple environments.
- There are times when you need to diagnose a problem and log out. In log4j, the only way to do this is to lower the logging level, which can result in a large number of logs that affect application performance. At Logback, you can keep that log level with the exception of some special cases, such as when Alice logs in, her log will be logged at DEBUG and other users can continue logging at WARN. All you need to do is add four lines of XML configuration. Refer to MDCFIlter.
- SiftingAppender (a very versatile Appender) : It can be used to split log files based on any given running parameter. For example, SiftingAppender can separate log events from each user’s Session and then have a log file for each user.
- Automatically compress outgoing log files: RollingFileAppender automatically compresses outgoing log files when a new file is created. Compression is an asynchronous process, so even for large log files, applications are unaffected during compression.
- Stack tree with package version: Logback takes the package data with it when it prints the stack tree log.
- Automatically remove old log files: You can control the maximum number of log files that have been generated by setting the maxHistory property of TimeBasedRollingPolicy or SizeAndTimeBasedFNATP. If maxHistory is set to 12, log files older than 12 months are automatically removed.
3. Logback configuration
- Logger, appender, and Layout
Logger serves as a log Logger. After being associated with an application context, Logger is used to store log objects and define log types and levels. Appenders are primarily used to specify log output destinations, which can be consoles, files, remote socket servers, MySQL, PostreSQL, Oracle, and other databases, JMS, and remote UNIX Syslog daemons. Layout is responsible for converting events into strings and formatting the output of log information.
- logger context
Each logger is associated with a LoggerContext, which is responsible for creating loggers and arranging them in a tree structure. All other loggers are 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 yields a reference to the same Logger object.
- Valid levels and level inheritance
Loggers can be assigned levels. Level include: TRACE, DEBUG, INFO, WARN, and the ERROR, defined in ch. Qos. Logback. Classic. Level class. If logger is not assigned a level, it inherits the level from the nearest ancestor that has the assigned level. The default logger level is DEBUG.
- Printing methods and basic selection rules
The printing method determines the level of logging requests. For example, if L is a Logger instance, then the statement L.info(“..” ) is a record statement at level INFO. A logging request is said to be enabled if its level is higher than or equal to the valid level of its Logger; otherwise, it is said to be disabled. Log request level is P, valid level of logger is Q, and the request will only be executed if p>= Q. This rule is at the heart of LogBack. The levels are in the following order: TRACE < DEBUG < INFO < WARN < ERROR 4
If neither the logback-test.xml nor logback.xml configuration files exist, logback by default calls BasicConfigurator to create a minimal configuration. The minimize configuration consists of a ConsoleAppender associated with the root Logger. The output is formatted with PatternLayoutEncoder with mode % D {HH:mm: ss.sss} [%thread] %-5level % Logger {36} – % MSG %n. The default logger level is DEBUG.
- Logback configuration file
The syntax of the Logback profile is very flexible. Because of its flexibility, it cannot be defined with a DTD or XML Schema. However, the basic structure of a configuration file can be described as starting with <configuration> followed by zero or more <appender> elements, zero or more <logger> elements, and at most one <root> element.
- Logback Default configuration step
- Try to find the file logback-test.xml in the classpath;
- If the file does not exist, look for the file logback.xml;
- If neither file exists, LogBack automatically configates itself with BasicConfigurator, which results in records being output to the console.
Logback. XML common configuration details
- (1) The root node < Configuration > contains the following three properties:
Scan: When this property is set to true, the configuration file will be reloaded if it changes. The default value is true. ScanPeriod: indicates the interval for checking whether the configuration file has been modified. If no time unit is given, the default unit is milliseconds. This attribute takes effect when scan is true. The default interval is 1 minute. Debug: When this attribute is set to true, internal logback logs are displayed to view the running status of logback in real time. The default value is false. Such as:
<configuration scan="true" scanPeriod="60 seconds" debug="false"> <! -- Other configuration omitted --> </configuration>Copy the code
- (2) child
: used to set the contextName. Each logger is associated with the logger context. The default contextName is default. However, it can be set to a different name using
to distinguish between records for different applications. Once set, it cannot be modified.
Such as:
< Configuration Scan ="true" scanPeriod="60 seconds" debug="false"> <contextName>myAppName</contextName> <! -- Other configuration omitted --> </configuration>Copy the code
- The
child node is used to define the variable value. It has two properties, name and value. The value defined by is inserted into the Logger context and can be used by “${}”.
Name: indicates the name of the variable. Value: indicates the value of the variable. Example:
< Configuration Scan ="true" scanPeriod="60 seconds" debug="false"> <property name="APP_Name" value="myAppName" /> The < contextName > ${APP_Name} < / contextName > <! -- Other configuration omitted --> </configuration>Copy the code
- (4) child
: gets the timestamp string, which has two attributes key and datePattern
Key: identifies the name of this
; DatePattern: set the current time (time) parsing the configuration file is converted into a string pattern, follow the Java. TXT. SimpleDateFormat format. Such as:
<configuration Scan ="true" scanPeriod="60 seconds" debug="false"> <timestamp key="bySecond" DatePattern = "yyyyMMdd 'T' HHmmss" / > < contextName > ${bySecond} < / contextName > <! -- Other configuration omitted --> </configuration>Copy the code
- (5) Child
: the component responsible for writing logs. It has two necessary properties name and class. Name specifies the name of the appender, and class specifies the fully qualified name of the appender
5.1 ConsoleAppender outputs logs to the console with the following subnodes:
: formats logs.
: the string system. out(the default) or system. err (the difference is not detailed), for example:
STDOUT < configuration > < appender name = "" class =" ch. Qos. Logback. Core. ConsoleAppender "> < encoder > <pattern>%-4relative [%thread] %-5level % Logger {35} - % MSG %n</pattern> </encoder> </appender> <root level="DEBUG"> <appender-ref ref="STDOUT" /> </root> </configuration>Copy the code
The above configuration means that >=DEBUG level logs are output to the console
5.2Fileappender: Adds logs to files with subnodes:
: Specifies the file name to be written to. It can be a relative or absolute directory. If the upper directory does not exist, it will be created automatically and has no default value.
: If true, the log is appended to the end of the file. If false, the existing file is emptied. The default is true.
: Formats the recorded events. < discard > : If true, logs are safely written to the file, even if other Fileappenders are also writing to the file. Default: false. Such as:
< configuration > < appender name = "FILE" class = "ch. Qos. Logback. Core. FileAppender" > < FILE >. TestFile log < / FILE > <append>true</append> <encoder> <pattern>%-4relative [%thread] %-5level % Logger {35} - % MSG %n</pattern> </encoder> </appender> <root level="DEBUG"> <appender-ref ref="FILE" /> < / root > < / configuration >Copy the code
The above configuration indicates that all >=DEBUG logs are output to testfile.log
5.3. RollingFileAppender: Logs are rolled to a specified file and to another file when a condition is met. There are subnodes:
: indicates the file name to be written to. It can be a relative or absolute directory. If the parent directory does not exist, it will be automatically created and has no default value.
: If true, the log is appended to the end of the file. If false, the existing file is emptied. The default is true.
: Determines the behavior of the RollingFileAppender when scrolling occurs, involving file movement and renaming. Properties define the specific rolling strategy class class class = “ch. Qos. Logback. Core. Rolling. TimeBasedRollingPolicy” : the most commonly used rolling strategy, rolling strategy according to the time, it is responsible for rolling is also responsible for rolling. Have the following nodes: < fileNamePattern > : necessary nodes, include the file name and conversion operator “% d”, “% d” can contain a Java. The text. The SimpleDateFormat specified time format, such as: % d} {yyyy – MM. If % D is used directly, the default format is YYYY-MM-DD. RollingFileAppender’s file byte point is optional. By setting file, you can specify different locations for active and archive files. The current log is always recorded to the file specified by File (the active file) and the name of the active file does not change. If file is not set, the name of the active file changes at regular intervals based on the value of fileNamePattern. “/” or “\” are used as directory separators.
: Optional node that controls the maximum number of archived files that can be retained and deletes old files if the number exceeds that. If monthly scrolling is set and
is 6, only files of the last 6 months are saved and old files of the previous period are deleted. Note that when old files are deleted, directories created for archiving are also deleted. Class = “ch. Qos. Logback. Core. Rolling. SizeBasedTriggeringPolicy” : the size of the file to view the current activity, if more than a specified size will inform RollingFileAppender trigger scroll the current active file. There is only one node:
: This is the size of the active file, default is 10MB.
: indicates the minimum window index value.
: indicates the maximum window index value. If the specified window is too large, the window is automatically set to 12.
: the value must contain % I. For example, if the minimum value is 1 and the maximum value is 2, and the naming mode is mylog%i.log, the archive files mylog1.log and mylog2.log are generated. You can also specify file compression options, for example, mylog%i.log.gz or no log%i.log.zip for example:
< configuration > < appender name = "FILE" class = "ch. Qos. Logback. Core. Rolling. RollingFileAppender" > < rollingPolicy class = "ch. Qos. Logback. Core. Rolling. TimeBasedRollingPolicy" > < fileNamePattern > logFile. % d - the dd} {yyyy - MM. The log < / fileNamePattern > < maxHistory > 30 < / maxHistory > </rollingPolicy> <encoder> <pattern>%-4relative [%thread] %-5level % Logger {35} - % MSG %n</pattern> </encoder> </appender> <root level="DEBUG"> <appender-ref Ref = "FILE" / > < / root > < / configuration >Copy the code
Note: The preceding configuration indicates that a log file is generated every day and saved for 30 days.
< configuration > < appender name = "FILE" class = "ch. Qos. Logback. Core. Rolling. RollingFileAppender" > < file >. The test log < / file > < rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy"> The < fileNamePattern > tests. % i.l og. Zip < / fileNamePattern > < minIndex > 1 < / minIndex > The < maxIndex > 3 < / maxIndex > < / rollingPolicy > < triggeringPolicy Class = "ch. Qos. Logback. Core. Rolling. SizeBasedTriggeringPolicy" > < maxFileSize > 5 MB < / maxFileSize > </triggeringPolicy> <encoder> <pattern>%-4relative [%thread] %-5level % Logger {35} - % MSG %n</pattern> </encoder> </appender> <root level="DEBUG"> <appender-ref Ref = "FILE" / > < / root > < / configuration >Copy the code
Note: the preceding configuration indicates that log files are generated in fixed window mode. When the size of a log file is larger than 20MB, a new log file is generated. The window size is 1 to 3, and when three archives are saved, the earliest log is overwritten.
: Formats the recorded events. It is responsible for converting log information into byte arrays and writing byte arrays to the output stream. PatternLayoutEncoder is the only useful and default encoder with a < Pattern > node that sets the input format for the log. Use “%” plus “conversion”. If you want to print “%”, you must escape “\%” with “\”. SocketAppender, SMTPAppender, DBAppender, SyslogAppender, and SiftingAppender are not commonly used. You can refer to the official documentation (http://logback.qos.ch/documentation.html), which can also write your own Appender.
- (6) Child node
: used to set the log printing level of a package or a specific class and specify
.
has only a name attribute, an optional level, and an optional addtivity attribute.
It can contain zero or more
elements that indicate that the appender will be added to the loger name: used to specify the package or class that is subject to the loger. Level: Used to set the printing level. This level is case-insensitive: TRACE, DEBUG, INFO, WARN, ERROR, ALL, and OFF. INHERITED or NULL represents the INHERITED level. If this property is not set, the current LOger inherits the level of the parent. Addtivity: Whether to convey printed information to the superior Loger. The default is true. As with
, it can contain zero or more
elements, indicating that the appender will be added to the LOger.
- (7) Child
: it is also a
element, but it is the root loger, the parent of all
. There is only one level attribute, because name is already named “root” and is already the highest level.
Level: This parameter is used to set the printing level. The value is case-insensitive: TRACE, DEBUG, INFO, WARN, ERROR, ALL, and OFF. INHERITED or NULL cannot be used. The default is DEBUG. Six, common LOger configuration
<! - show the parameters for SQL for hibernate hibernate custom - > < logger name = ". Org. Hibernate. The type descriptor. SQL. BasicBinder" level="TRACE" /> <logger name="org.hibernate.type.descriptor.sql.BasicExtractor" level="DEBUG" /> <logger name="org.hibernate.SQL" level="DEBUG" /> <logger name="org.hibernate.engine.QueryParameters" level="DEBUG" /> <logger name="org.hibernate.engine.query.HQLQueryPlan" level="DEBUG" /> <! --myibatis log configure--> <logger name="com.apache.ibatis" level="TRACE"/> <logger name="java.sql.Connection" level="DEBUG"/> <logger name="java.sql.Statement" level="DEBUG"/> <logger name="java.sql.PreparedStatement" level="DEBUG"/>Copy the code
Seven, the Demo
- Slf4j-api = slf4J-API = slf4J-API = slf4J-API = slf4J-API = slf4j-API
Jar, logback-classic.jar, logback-access.jar, slf4j-api.jar, logback-classic.jar, logback-access.jar Maven configuration
< the properties > < project. Build. SourceEncoding > utf-8 < / project. Build. SourceEncoding > < logback version > 1.1.7 < / logback version > < slf4j. Version > 1.7.21 < / slf4j version > < / properties > < dependencies > < the dependency > < groupId > org. Slf4j < / groupId > < artifactId > slf4j - API < / artifactId > . < version > ${slf4j version} < / version > < scope > compile < / scope > < / dependency > < the dependency > < the groupId > ch. Qos. Logback < / groupId > < artifactId > logback - core < / artifactId > < version > ${logback. Version} < / version > < / dependency > < the dependency > < groupId > ch. Qos. Logback < / groupId > < artifactId > logback - classic < / artifactId > < version > ${logback. Version} < / version > < / dependency > </dependencies>Copy the code
- (2) Logback.xml configuration
<? The XML version = "1.0" encoding = "utf-8"? > <configuration debug="false"> <! <property name="LOG_HOME" value="/home" /> <! - the console output - > < appender name = "STDOUT" class = "ch. Qos. Logback. Core. ConsoleAppender" > < encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder"> <! Format output: %d indicates the date, %thread indicates the thread name, %-5level indicates the level from the left 5 character width % MSG: Log messages, SSS} [%thread] %-5level % Logger {50} - % MSG %n</pattern> </encoder> </appender> <! Generated according to the daily log FILE - > < appender name = "FILE" class = "ch. Qos. Logback. Core. Rolling. RollingFileAppender" > < rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <! ${LOG_HOME}/ testWeb.log.%d{YYYY-MM-DD}. Log </FileNamePattern> <! -- Log file retention days --> <MaxHistory>30</MaxHistory> </rollingPolicy> <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder"> <! Format output: %d indicates the date, %thread indicates the thread name, %-5level indicates the level from the left 5 character width % MSG: -> <pattern>%d{YYYY-MM-DD HH: MM :ss.SSS} [%thread] %-5level % Logger {50} - % MSG %n</pattern> </ coder> <! -- the largest size in the log file -- > < triggeringPolicy class = "ch. Qos. Logback. Core. Rolling. SizeBasedTriggeringPolicy" > <MaxFileSize>10MB</MaxFileSize> </triggeringPolicy> </appender> <! <root level="INFO"> <appender-ref ref="STDOUT" /> </root> </configuration>Copy the code
- (3) Java code
/ * * * Hello world! 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 "); }}Copy the code
- (4) Output
Eight, summary
To configure logback, you need to configure the output source appender, loger (child node) and root (root node) of the log. In fact, it outputs logs from the child node. If the child node has an output source input directly, if not, it judges whether the addtivity of the configuration is passed from superior to superior. That is, whether to send logs to root, the root output source is used. Otherwise, logs are not generated.
The foolish old man walking on the clouds
The editor
collection
FeedBack:
# 1 / f,
Attack of rice rice
Support (0)
Against (0)
# 2 floor
The foolish old man walking on the clouds
@
Support (0)
Against (0)
The # 3 floor
Gonjian
Support (0)
Against (0)
# 4 floor
The foolish old man walking on the clouds
Support (0)
Against (0)
The # 5 floor
youzhibing2904
Support (0)
Against (0)
# 6 building
Old walking bear
Support (0)
Against (0)
# 7 floor
wangxiaoan1234
Support (0)
Against (0)
# 8 floor,
Have you in my life
Support (0)
Against (0)
# 9 / f,
The code to fly
Support (0)
Against (0)
# 10 floor
The foolish old man walking on the clouds
@
Support (0)
Against (0)
# 11 floor
specialangel
Support (0)
Against (0)
# 12 floor
The foolish old man walking on the clouds
@
Support (0)
Against (0)
# 13 floor
Bounty hunter Surfing
Support (0)
Against (0)
# 14 floor
jiewolf
Support (0)
Against (0)
# 15 floor
The foolish old man walking on the clouds
@
Support (0)
Against (0)
# 16 floor
badyu
Support (0)
Against (0)
# 17 floor
Invincible Little Arno
Support (0)
Against (0)
# 18 building
The foolish old man walking on the clouds
@
Support (0)
Against (0)
# the 19th floor
LUOLOVELUO
Support (0)
Against (0)
# 20 buildings
LeiKaiKai
Support (0)
Against (0)
# 21 floor
LeiKaiKai
@
Support (0)
Against (0)
# 22 floor
The foolish old man walking on the clouds
@
Support (0)
Against (0)
# 23 f
Fools on the road
Support (0)
Against (0)
Refresh the comments
Refresh the page
Return to the top
The login
registered
access
More than 500,000 VC++ source code: large configuration industrial control, power simulation CAD and GIS source code library!
[Activity] 11.1-11.11, 3000 yuan god coupon limited snatching, 51CTO full course 50% off, but also send exquisite gifts!
[Recommended] Huawei Cloud 11.11 Universal Shopping storm immediately started
[Tools] SpreadJS pure front-end table control, can be embedded in the application development of online Excel
[Tencent Cloud] Group benefits, AMD cloud server 8 yuan/month
System recommends blog posts
Configure and use logBack
Slf4j in combination with LogBack
Use the logback.xml configuration to implement log file output
Logback usage and interpretation of configuration files
Logback Usage details
Latest Knowledge Base articles
Programmer: Change the world with code
These crazy people at Aliyun
Why do Java programmers have to master Spring Boot?
In learning, there is a more important ability than mastering knowledge
How to recruit a reliable programmer
More knowledge base articles…
The foolish old man walking on the clouds
Three years and three months
31
1
+ add attention
|
||||||
day | one | two | three | four | five | six |
---|---|---|---|---|---|---|
28 | 29 | 30 | 31 | 1 | 2 | 3 |
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 1 |
2 | 3 | 4 | 5 | 6 | 7 | 8 |
search
Commonly used links
- My essay
- My comments
- I participate in
- The latest comments
- My label
My label
- python(10)
- git(5)
- Distributed Cache (4)
- Cache (4)
- memcached(4)
- zookeeper(3)
- JAVA(2)
- logback(1)
- logback.xml(1)
- lombok(1)
- More and more
Classification of essays
- docker
- git(5)
- Hadoop
- Java(5)
- Linux(1)
- Memcached(5)
- python(11)
- rocketmq
- spring(1)
- Zookeeper(3)
- algorithm
Archives of essays
- December 2017 (2)
- November 2017 (1)
- September 2017 (3)
- August 2017 (2)
- July 2017 (13)
- May 2017 (4)
- April 2017 (2)
- July 2016 (2)
- July 2015 (1)
The latest comments
- 1. Re: The use of logback and logback.xml details
- There are times when you need to diagnose a problem and log out. In log4j, the only way to do this is to lower the logging level, which can result in a large number of logs that affect application performance. At Logback, you can keep that log level without any special……
- — A fool on the road
- 2. Re: The use of logback and logback.xml details
- @luoloveluoSpring Boot does not specify log output to log file by default. You need to add log output configuration to application. Yml (or application
- — Foolish old man walking on the clouds
- 3. Re: The use of logback and logback.xml details
- Hello @luoloveluo Did you fix the empty log file? .
- – LeiKaiKai
- 4. Re: Use of logback and logback.xml details
- The logback. XML configuration can generate.log files, but the log file is empty
- – LeiKaiKai
- 5. Re: The use of logback and logback.xml details
- I used logback in my Spring Boot project, but the log information was not written into the log file. About logback. XML, I copied it from yours and also generated E:// testweb. log, but it is……
- –LUOLOVELUO
Reading leaderboards
- 1. The use of logback and logback.xml (191273)
- 2. Solve git newline consistency problem in different operating systems (5019)
- 3. The company has been using Lombok recently, and it feels very good about it. So I searched some information on the Internet and summarized its usage. (866).
- 4. Zookeeper Deployment and Running (112)
- 5. Linux Package Manager (103)
Review charts
- Logback: logback.xml
Recommended leaderboard
- Logback: logback.xml
Blog garden
Hj blog