Preface
1、There is a complete configuration file at the end
2. Logs are divided into five levels, which can be divided into:
TRANCE < DEBUG < INFO < WARN < ERROR
springboot
The default isINFO
, therefore lower thanINFO
ofTRACE
andDEBUG
No output will be made.
Can beproperties
oryaml
Modify log level in the configuration file:
logging: level: root: debug
Hereroot
It can be replaced with the package name to finely control the log output levels of different packages, such as:
logging: level: : debug : error
3. Secondly, logback's logs are divided into console logs and file logs.
Console log: That is, the information printed by the console when our IDE runs the project.
File log: When the project is running, the run information is written to the specified file. Need to be inspringboot
Configuration file orlogback
Specifies the location of the log file in the configuration file.
Introduce dependencies
<dependency> <groupId></groupId> <artifactId>spring-boot-starter-logging</artifactId> </dependency>
Explanation: What needs to be introduced in theory isspring-boot-starter-logging
Depend on, butspring-boot-starter-web
Indirectly depend onspring-boot-starter-logging
, so we just need to introducespring-boot-starter-web
Just do it.
Using logback
logback
Will automatically searchclasspath
Below the root, so we just need to
resource
Created in the directoryFiles can automatically load the configuration files of the custom log when the program starts.
If you don't want to call, remember a name with personality, for example
, then it needs to be
properties
oryaml
Configuration file specificationlogback
File path:
logging: config: classpath:
If you want to verify it, you can copy the configuration file in the overview below to your own project and run it, and observe the console's log output format.
Configuration file overview
You can simply look at a configuration file case
<?xml version="1.0" encoding="UTF-8"?> <!-- scan:When the configuration file is modified,Will be reloaded。 scanPeriod:Set the time interval to detect whether the configuration file has been modified,If no time unit is given,The default unit is milliseconds。whenscanfortruehour,This property takes effect。 debug:fortruehour,Will print outlogbackInternal log information,实hour查看logbackRunning status。默认值forfalse。 --> <configuration scan="true" scanPeriod="60 seconds" debug="false"> <!-- 定义一个名forSTDOUTconsole outputAppender --> <appender name="STDOUT" class=""> <encoder> <!-- Output format --> <pattern>%d{HH:mm:} [%thread] %-5level %logger{36} - %msg%n</pattern> </encoder> </appender> <!-- 定义一个名forFILEFile outputAppender --> <appender name="FILE" class=""> <!-- Set the log file storage path and file name,Can be modified according to actual situation --> <file>logs/</file> <encoder> <pattern>%d{HH:mm:} [%thread] %-5level %logger{36} - %msg%n</pattern> </encoder> </appender> <!-- Configure the root logger,设置日志级别forDEBUG,and output the log toSTDOUTandFILEThese twoAppender --> <root level="info"> <appender-ref ref="STDOUT" /> <appender-ref ref="FILE" /> </root> </configuration>
This file mainly defines twoAppender
, output logs to the console and files respectively.
Second definitionroot
The log level of the directory and the twoAppender
Configure toroot
In the directory, log output is performed.
Hereroot
It is defined in the taglevel
, Have you ever seen this thing somewhere?
That's right, as mentioned above, we canproperties
oryaml
Modify the log level in the configuration file,springboot
The operations in the configuration file are equivalent to the operations here. Then according to the same principle, hereroot
It can also be refined into different packages and configured with different configurations.level
andAppender
. This is just a concept that is introduced here, and the specific content is placed below.
Detailed explanation of configuration items
<configuration>
: The root tag of logback configuration. It contains three properties:scan
、scanPeriod
、debug
。
-
scan
: When the configuration file is modified, it will be reloaded. The value istrue
orfalse
。 -
scanPeriod
: Time interval. Check whether the configuration file is modified every once in a while. The value can be60
or12 second
, the numbers are customized, it is not necessary to fill in60
or12
, if no time unit is given, the default unit is milliseconds. whenscan
fortrue
This property takes effect when . -
debug
: Whether to printlogback
Internal log information, real-time view of logback running status. The value istrue
orfalse
(default).
<Appender>
: It can be understood as a tool person responsible for writing logs. oneAppender
It's a tool person.
<logger>
: Set the log printing level of a package or specific class, and the specifiedAppender
(Assign workers).
<root>
:rootlogger
,Toologger
There is only one type oflevel
property.
contextName
:Eachlogger
All are related tologger
Context, default context name isdefault
. But it can be usedcontextName
Tags are set to other names to distinguish records from different applications.
property
: The label used to define the value of the variable,property
The tag has two attributes.name
andvalue
;inname
The value of the variable is the name of the variable.value
The value of the variable is defined. passproperty
The defined value will be inserted intologger
in context. After defining the variable, you can make“${name}”
to use variables.
Appender
kind of:
- ConsoleAppender:Console log.
- FileAppender: File log.
- RollingFileAppender: Scroll file logs. After the log file meets a certain condition, a new log file will be created and continued to be written to the log. A common condition is the size of the file. For example, when setting the size of each file to 2KB, create a new file and continue writing, with the file name roughly,.
Detailed explanation of the output format
For example:%level | %d{yyyy-MM-dd HH:mm:ss,Asia/Shanghai} | [%thread] | %-4relative | %logger{40}| -- %msg%n
%level
: Log level.
%d{yyyy-MM-dd HH:mm:ss,Asia/Shanghai}
:time.
[%thread]
: The current thread.
%-4relative
: The relative time elapsed from the start of the program to the current logging event.-
Indicates left alignment,4
Represents 4 characters width.
%logger{40}
: The placeholder for outputting the logger name, where40
Is an optional parameter that specifies the maximum length of the output logger name. If not specified{40}
Such parameters will output the complete logger name by default.
%msg
: Log message body.
%n
: Line break.
%file
:file name.
%line
: Line number.
Configuration file example
<?xml version="1.0" encoding="UTF-8"?> <!-- scan:When the configuration file is modified,Will be reloaded。 scanPeriod:Set the time interval to detect whether the configuration file has been modified,If no time unit is given,The default unit is milliseconds。whenscanfortruehour,This property takes effect。 debug:fortruehour,Will print outlogbackInternal log information,实hour查看logbackRunning status。默认值forfalse。 --> <configuration scan="true" scanPeriod="60 seconds" debug="false"> <!-- Log file path,ifspringThere is no corresponding value for the configuration file,Use default values --> <springProperty scope="context" name="springFilePath" source="" defaultValue="src/main/resources/log"/> <!-- Output logs to console --> <appender name="console" class=""> <encoder> <pattern>%level | %d{yyyy-MM-dd HH:mm:ss,Asia/Shanghai} | [%thread] | %-4relative | %logger{40}| -- %msg%n</pattern> <charset>UTF-8</charset> </encoder> </appender> <!-- Output logs to file --> <!-- Use Rotary Log:After the log file exceeds a certain size,A new file will be created(Rolling) --> <appender name="file" class=""> <!-- Set file path --> <file>${springFilePath}/</file> <encoder class=""> <pattern>%d{yyyy-MM-dd HH:mm:} %-5level %thread -- %msg%n</pattern> <charset>utf-8</charset> </encoder> <!-- 基于hour间和大小的滚动策略 --> <rollingPolicy class=""> <!-- File name output from log file --> <fileNamePattern>${springFilePath}/spring.%d{yyyy-MM-dd}.%</fileNamePattern> <!-- Maximum volume of a single log file,Exceeded maximum value,A new log file will be created--> <maxFileSize>200MB</maxFileSize> <!-- Number of days of log file retention --> <maxHistory>60</maxHistory> <!-- Total volume limit for all log files --> <totalSizeCap>20GB</totalSizeCap> </rollingPolicy> </appender> <!-- root节点hour必选节点,Used to specify the most basic log output level,Only onelevelproperty --> <root level="info"> <appender-ref ref="console" /> <appender-ref ref="file" /> </root> </configuration>
Configure color for logs
Method 1: Use the official default configuration
Just introduce the configuration file into the XML configuration file.
<include resource="org/springframework/boot/logging/logback/"/>
What? You ask me where to find this file? according toresource
The path inside is found in the springboot dependency of the lib directory.
Method 2: Custom color configuration
Use shape like%clr(){red}
Let's configure the color of the log label.
To use%clr
, there are two ways:
The first is to introduce the default configuration file of Method 1, which helps us introduce it in this file.%clr
。
The second method is to introduce it manually%clr
, you can refer to it。
<conversionRule conversionWord="clr" converterClass="" />
%clr
Supported colors: blue, cyan, faith, green, magenta, red, yellow
faint
: Light color (console default color)
magenta
: Magenta
Post mine herepattern
%level | %clr(%d{yyyy-MM-dd HH:mm:ss,Asia/Shanghai}){magenta} | [%thread] | %-4relative | %clr(%logger{40}){magenta}| -- %msg%n
Then you will find that if you customize this way, why does my level have no color?
Don't worry, there is a solution.
Here are two solutions:
The first one can be changedlogback
middle,%clr
The judgment of level is differentlevel
Show different colors, but I don't know this yet, so I explore it myself.
The second one is%highlight
Highlight.
Use %highlight to configure color for level
The first step is to create a new highlight color configuration class.
import ; import ; import ; import static .*; import static .DEFAULT_FG; /** * Custom %highlight to implement different log levels and colors */ public class LevelHighLightColorConfig extends HighlightingCompositeConverter { // The version used here is springboot 2.6.13 // If you find that the method in the parent class is not getForegroundColorCode, it may be caused by the version difference. // Then you need to click on the parent class ctrl+left click to see how the parent class is implemented // Then continue to modify it according to the cat and the tiger. The core logic is to judge and return to different colors. // Because this happens when the author follows the AI configuration, he also imitates the parent class to modify it. @Override protected String getForegroundColorCode(ILoggingEvent event) { Level level = (); switch (()) { case Level.ERROR_INT: return RED_FG; case Level.WARN_INT: return YELLOW_FG; case Level.INFO_INT: return GREEN_FG; default: return DEFAULT_FG; } } }
Step 2:Introduce our configuration file
%highlight
conversionWord
The value ofhighlight
,converterClass
The value of the configuration class we wrote in the previous step.
<conversionRule conversionWord="highlight" converterClass="" />
Step 3: Writingpattern
<pattern>%highlight(%level) | %clr(%d{yyyy-MM-dd HH:mm:ss,Asia/Shanghai}){magenta} | [%thread] | %-4relative | %clr(%logger{40}){magenta}| -- %msg%n</pattern>
Complete configuration file
<?xml version="1.0" encoding="UTF-8"?> <!-- scan:When the configuration file is modified,Will be reloaded。 scanPeriod:Set the time interval to detect whether the configuration file has been modified,If no time unit is given,The default unit is milliseconds。whenscanfortruehour,This property takes effect。 debug:fortruehour,Will print outlogbackInternal log information,实hour查看logbackRunning status。默认值forfalse。 --> <configuration scan="true" scanPeriod="60 seconds" debug="false"> <include resource="org/springframework/boot/logging/logback/"/> <conversionRule conversionWord="highlight" converterClass="" /> <!-- Log file path,ifspringThere is no corresponding value for the configuration file,Use default values --> <springProperty scope="context" name="springFilePath" source="" defaultValue="src/main/resources/log"/> <!-- Output logs to console --> <appender name="console" class=""> <encoder> <pattern>%highlight(%level) | %clr(%d{yyyy-MM-dd HH:mm:ss,Asia/Shanghai}){magenta} | [%thread] | %-4relative | %clr(%logger{40}){magenta}| -- %msg%n</pattern> <charset>UTF-8</charset> </encoder> </appender> <!-- Output logs to file --> <!-- Use Rotary Log:After the log file exceeds a certain size,A new file will be created(Rolling) --> <appender name="file" class=""> <!-- Set file path --> <file>${springFilePath}/</file> <!-- 基于hour间和大小的滚动策略 --> <rollingPolicy class=""> <!-- File name output from log file --> <fileNamePattern>${springFilePath}/spring.%d{yyyy-MM-dd}.%</fileNamePattern> <!-- Maximum volume of a single log file,Exceeded maximum value,A new log file will be created--> <maxFileSize>200MB</maxFileSize> <!-- Number of days of log file retention --> <maxHistory>60</maxHistory> <!-- Total volume limit for all log files --> <totalSizeCap>20GB</totalSizeCap> </rollingPolicy> <encoder class=""> <pattern>%d{yyyy-MM-dd HH:mm:} %-5level %thread -- %msg%n</pattern> <charset>utf-8</charset> </encoder> </appender> <!-- root节点hour必选节点,Used to specify the most basic log output level,Only onelevelproperty --> <root level="info"> <appender-ref ref="console" /> <appender-ref ref="file" /> </root> </configuration>1
Tips 1. File path configuration problem
There are two ways to configure the file path, namelyfile
andpath
, or configure it in the xml file.
Note:fileandpathBoth cannot be used at the same time,If used at the same time,Only effective =file name =Log file path .Package name=Specify the log level under the package =Log printing rules
- , set the file, which can be an absolute path or a relative path. like:
=
- , set the directory, create a file in this directory and write the log content, such as:
=/var/log
Note: Both cannot be used at the same time. If used at the same time, it will only take effect. You can see that this method is simple to configure, but the functions that can be implemented are also very limited. If you want more complex requirements, you need the followingCustomized configurationNow.
2. Use %clr to add color and start the error
The complete error is as follows:
Exception in thread "main" : Logback configuration error detected: ERROR in @7a362b6b - There is no conversion class registered for composite conversion word [clr] ERROR in @7a362b6b - Failed to create converter for [%clr] keyword ERROR in @7a362b6b - There is no conversion class registered for composite conversion word [clr] ERROR in @7a362b6b - Failed to create converter for [%clr] keyword at (:166) at (:82) at (:60) at (:114) at (:264) at (:237) at (:200) at (:173) at (:172) at (:165) at (:139) at (:127) at (:74) at (:54) at (:358) at (:317) at (:1255) at (:1243) at (:24)
Solution:
No introduction%clr
, the default configuration file needs to be introduced
<include resource="org/springframework/boot/logging/logback/"/>
Or manually introduced%clr
<conversionRule conversionWord="clr" converterClass="" />
3. Do not use color output in log files
Using color output will convert the color to ANSI code, there will be no color and poor readability.
Reference link
【1】SpringBoot+logback elegant configuration log
【2】Logback official configuration document
This is the end of this article about springboot using logback custom logs. For more related springboot logs, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!