- Simple Log Configuration
- This section describes how to configure logBack
- The use of logback
- Logback. XML configuration example
I. Simple log configuration
Spring Boot uses Commons Logging internally for Logging, but also retains external interfaces for Logging frameworks such as Java Util Logging,Log4J2, and Logback. If you want to use one of these logging frameworks, you must configure it first. By default, Spring Boot uses Logback as the logging framework.
1.1 Configuring the Debug Level of Console Logs By default, Spring Boot prints logs from the console at ERROR, WARN, and INFO. If you want to print debug logs, Debug =true can be configured with application.properites
1.2 In the production environment, you can configure the debug level of logs using the cli Java -jar C:\Users\Administrator\app\xx\demo.jar –debug
1.3 configuration logging. Level. * to specific output which packages the log level of logging. Level. The root = INFO logging.level.org.springframework.web=DEBUG logging.level.org.hibernate=ERROR
By default, Spring Boot does not export logs to log files, but you can configure the logging.file name and logging.path in the application.properites file. Path =F:\demo logging.file=demo.log logging.level.root=info
Note the following: If the log level of the specific package is not configured, the log file information will be empty. If only logging.path is configured, a log file named spring.log will be generated in the F:\demo folder (the file name is fixed and cannot be changed). If the path path does not exist, the folder will be created automatically. If only logging.file is configured, a demo.log log file will be generated in the current path of the project. The absolute path can be used. For example, the system automatically creates folders and corresponding log files in drive E. logging.file=E:\demo\demo.log
Path and logging.file are configured at the same time. F:\demo\demo.log will not be generated in this path. Logging. path and logging.file are not superimposed (note that the values of logging.path and logging.file can be relative or absolute paths, which is the basic logging configuration. This can be configured directly in application.properties or by defining the specific log file — logback.xml in the classpath path
Introduction and configuration of logBack
Logback is another open source logging component designed by the log4J founders. Logback is currently divided into three modules: logback-core, logback-classic, and logback-access. Logback-core is the base module for the other two modules. Logback-classic is an improved version of Log4J. In addition, logback-classic fully implements the SLF4J API so that you can easily switch to other Logging systems such as Log4J or JDK14 Logging. The logback-Access access module integrates with the Servlet container to provide log access over Http. Logback is to be combined with SLF4J using two components as follows
Maven configuration
< the groupId > ch. Qos. Logback < / groupId > < artifactId > logback - classic < / artifactId > < version > 1.0.11 < / version > < / dependency >Copy the code
Logback and Log4J are very similar, and if you are familiar with log4j, Logback will quickly become comfortable. Here are some of the advantages of LogBack over log4j:
1. The kernel was rewritten to implement Logback faster, 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.
Logback has been tested for years and countless hours. Logback tests are at a completely different level. In the author’s opinion, this is the simple and important reason to choose LogBack over Log4j.
3. Logback-classic implements SLF4j. In SLF4j, you will not 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.
4. Automatic reloading of the configuration file When the configuration file is modified, logback-classic automatically reloads the configuration file. 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.
5. Configuration files can handle different situations developers often need to judge different Logback configuration files 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 will be 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) 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.
The logRollingFileappender automatically compresses the logfile appender when it generates a new file. Compression is an asynchronous process, so even for large log files, applications are unaffected during compression.
When Logback prints the stack tree log, it carries the package’s data with it.
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.
2.3 This section describes how to configure Logback
Logger, as a log Logger, is used to store log objects and define log types and levels after being associated with an application context. 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.
LoggerContext Each logger is associated with a LoggerContext, which is responsible for creating loggers and arranging them in a tree. 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.
A valid level and its descendants can be assigned a level to a Logger. 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 method and Basic selection rules The printing method determines the level of record 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
Use of Logback
Logback
Scan: When this attribute is set to true, the configuration file will be reloaded if it changes. The default value is true. 2,scanPeriod: sets the interval for monitoring 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. 3. Debug: If this attribute is set to true, internal logback logs are displayed to view the logback running status in real time. The default value is false. Child element: : context name; : defines attributes, which can be used in configuration files using ${}; Logback is a component used to record logs. It can be used to configure the log recording mode and format. Properties include: name: The name of the appender, which is specified during logging configuration. Class: The appender class to use; Common appender: 1, ch. Qos. Logback. Core. ConsoleAppender: output to the console; 2, ch. Qos. Logback. Core. FileAppender: output to a file; 3, ch. Qos. Logback. Core. Rolling. RollingFileAppender: output to a file, you can configure the rolling strategy, when the log reaches a certain condition after points file records; 4. There are other appenders, such as writing to databases. The basic format of the element:… The %logger{n} element is used to specify the format of the log output. All expressions begin with % followed by a special identifier. Common identifiers are: 1, %logger{n} : the name of the output logger object class. 2, %class{n}: indicates the name of the output class. 3, d{pattern} or date{pattern} : indicates the date of the output log, in the same format as Java. 4, L/line: indicates the line number of the log. 5, m/ MSG: log content; 6, method: name of the method; 7, p/level: indicates the log level. 8, Thread: the name of the thread.
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.
1. Logback configuration file The Logback configuration file has a flexible syntax. 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 follows: start with, followed by zero or more elements, zero or more elements, and at most one element.
2. Logback steps for the default configuration
(1). Try to find logback-test.xml file in classpath; (2). If the file does not exist, find the file logback.xml; (3). If neither file exists, Logback automatically configures itself with the Bas icConfigurator, which causes the record to be output to the console.
Logback-spring. XML file
XML or logback-spring. XML is supported by default. Logback-spring. XML is recommended because SpringBoot provides additional functions.
<? xml version="1.0" encoding="UTF-8"? > <configuration debug="false"> <! Do not use a relative path in LogBack configuration --> <property name="LOG_PATH" value="/path"/ > <! 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> <! <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <! -- Log file output file name --> <FileNamePattern>${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> <! --> <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> <MaxFileSize>10MB</MaxFileSize> </triggeringPolicy> </appender> <! -- show parametersforHibernate SQL is customized for Hibernate --> < Logger name="org.hibernate.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"/ > <! --myibatislog 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"/ > <! -- Log output level --> <root level="INFO">
<appender-ref ref="STDOUT" />
<appender-ref ref="FILE"/> </root> <! Log asynchronize to database --> <appender name="DB" class="ch.qos.logback.classic.db.DBAppender"> <! -- Log async to database --> <connectionSource class="ch.qos.logback.core.db.DriverManagerConnectionSource"> <! --> <dataSource class="com.mchange.v2.c3p0.ComboPooledDataSource". > < driverClass > com. Mysql. JDBC Driver < / driverClass > < url > JDBC: mysql: / / 127.0.0.1:3306 / databaseName < / url > < user > root < / user > <password>root</password> </dataSource> </connectionSource> </appender> </configuration>Copy the code
3.2 Use a reference Logback in the program
package com.jd.springboot; import org.slf4j.Logger; import org.slf4j.LoggerFactory; Public class HelloController{// Define a global logger, Private final static Logger Logger = LoggerFactory.getLogger(helloController.class); public static void main(String[] args) { logger.info("Logback succeeded.");
logger.error("Logback succeeded."); }}Copy the code
Example of logback. XML configuration
<? xml version="1.0" encoding="UTF-8"? > <configuration> <! Note: 1. Log levels and files Logs are recorded at different levels and file names. Log information at different levels is recorded in different log files. Log (the current log file), and log_error_XXx. log (the archive log file). Log files are recorded by date. If the size of a log file is 10 MB or larger in the same day, Press 0, 1, 2... The order is named for examplelog-level-2018-12-28.0. Log The same is true for logs of other levels. If you are developing, testing, and running your project in Eclipse, go to the installation path of Eclipse and look for the logs folder to find the relative path.. / logs. If Tomcat is deployed, log files in Tomcat. Appender FILEERROR corresponds to the error level and file name is Appenderlog-error-xxx.log FILEWARN corresponds to the WARN level and is named in the format oflog- WARn-xxx. log FILEINFO corresponds to the info level and is named in the following formatlog- Info-xxx. log FILEDEBUG corresponds to the debug level and the file name islog-debug-xxx.log Stdout outputs log information to the control, which is used for development and testing. -> <contextName>SpringBootDemo</contextName> <property name="LOG_PATH" value="D:\\JavaWebLogs"/ > <! --> <property name="APPDIR" value="SpringBootDemo"/ > <! -- logger, date scrolling --> <appender name="FILEERROR" class="ch.qos.logback.core.rolling.RollingFileAppender"> <! -- The path and name of the log file being recorded --> <file>${LOG_PATH}/${APPDIR}/log_error.log</file> <! -- logger rollingPolicy, record by date, record by size --> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <! For example, the log file is 2013-12-21 today. The current log file path is specified by the file node. You can set the path of this file and file to different directories to save the current and archive log files. The log file of 2018-12-28 is specified by fileNamePattern. %d{YYYY-MM-DD} specifies the date format, % I specifies the index --> <fileNamePattern>${LOG_PATH}/${APPDIR}/error/log-error-%d{yyyy-MM-dd}.%i.log</fileNamePattern> <! -- In addition to logging, the log file cannot exceed 2M. If the log file exceeds 2M, the log file is named starting with index 0, for examplelog- error - 2018-12-28. 0. The log - > < timeBasedFileNamingAndTriggeringPolicy class ="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> <maxFileSize>10MB</maxFileSize> </timeBasedFileNamingAndTriggeringPolicy> </rollingPolicy> <! --> <append>true</append> <! -- Log file format --> <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder"> <pattern>===%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger Line:%-3L - %msg%n</pattern> <charset>utf-8</charset> </encoder> <! -- This log file records only info -> <filter class="ch.qos.logback.classic.filter.LevelFilter"> <level>error</level> <onMatch>ACCEPT</onMatch> <onMismatch>DENY</onMismatch> </filter> </appender> <! -- logger, date scrolling --> <appender name="FILEWARN" class="ch.qos.logback.core.rolling.RollingFileAppender"> <! -- The path and name of the log file being recorded --> <file>${LOG_PATH}/${APPDIR}/log_warn.log</file> <! -- logger rollingPolicy, record by date, record by size --> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <! -- The path of the archive log file, for example, 2018-12-28, is specified by the file node. You can set the path of the archive log file and the path of the file specified by the file node to different paths, so that the current and archive log files are placed in different directories. The log file of 2018-12-28 is specified by fileNamePattern. %d{YYYY-MM-DD} specifies the date format, % I specifies the index --> <fileNamePattern>${LOG_PATH}/${APPDIR}/warn/log-warn-%d{yyyy-MM-dd}.%i.log</fileNamePattern> <! If the log file size exceeds 10 MB, the log file name starts with index 0. For example, if the log file size exceeds 10 MB, the log file name starts with index 0log- error - 2018-12-28. 0. The log - > < timeBasedFileNamingAndTriggeringPolicy class ="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> <maxFileSize>10MB</maxFileSize> </timeBasedFileNamingAndTriggeringPolicy> </rollingPolicy> <! --> <append>true</append> <! -- Log file format --> <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder"> <pattern>===%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger Line:%-3L - %msg%n</pattern> <charset>utf-8</charset> </encoder> <! -- This log file records only info -> <filter class="ch.qos.logback.classic.filter.LevelFilter"> <level>warn</level> <onMatch>ACCEPT</onMatch> <onMismatch>DENY</onMismatch> </filter> </appender> <! -- logger, date scrolling --> <appender name="FILEINFO" class="ch.qos.logback.core.rolling.RollingFileAppender"> <! -- The path and name of the log file being recorded --> <file>${LOG_PATH}/${APPDIR}/log_info.log</file> <! -- logger rollingPolicy, record by date, record by size --> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <! -- The path of the archive log file, for example, 2018-12-28, is specified by the file node. You can set the path of the archive log file and the path of the file specified by the file node to different paths, so that the current and archive log files are placed in different directories. The log file of 2018-12-28 is specified by fileNamePattern. %d{YYYY-MM-DD} specifies the date format, % I specifies the index --> <fileNamePattern>${LOG_PATH}/${APPDIR}/info/log-info-%d{yyyy-MM-dd}.%i.log</fileNamePattern> <! If the log file size exceeds 10 MB, the log file name starts with index 0. For example, if the log file size exceeds 10 MB, the log file name starts with index 0log- error - 2018-12-28. 0. The log - > < timeBasedFileNamingAndTriggeringPolicy class ="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> <maxFileSize>10MB</maxFileSize> </timeBasedFileNamingAndTriggeringPolicy> </rollingPolicy> <! --> <append>true</append> <! -- Log file format --> <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder"> <pattern>===%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger Line:%-3L - %msg%n</pattern> <charset>utf-8</charset> </encoder> <! -- This log file records only info -> <filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>info</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <! -- Encoder defaults to PatternLayoutEncoder--> <encoder> <pattern>===%d{YYYY-MM-DD HH: MM: ss.sss} %-5level % Logger Line:%-3L - %msg%n</pattern> <charset>utf-8</charset> </encoder> <! This log appender is configured for development purposes only at the lowest level. The console outputs logs with a log level greater than or equal to this level --> <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>debug</level>
</filter>
</appender>
<logger name="org.springframework" level="WARN" />
<logger name="org.hibernate" level="WARN"/ > <! -- In the production environment, set this level to an appropriate level to avoid excessive log files or affecting program performance --> <root level="INFO">
<appender-ref ref="FILEERROR" />
<appender-ref ref="FILEWARN" />
<appender-ref ref="FILEINFO"/ > <! <appender-ref ref="STDOUT" />
</root>
</configuration>
Copy the code
Click on the SpringBoot tutorial from beginner to advanced video