web123456

SpringBoot integration Logback logging framework configuration analysis

One,LogbackIntroduction to Logframe

SpringBoot uses Commons Logging for all internal logging, but the default configuration also provides support for commonly used logging, such as Java Util Logging.Log4J2, and Logback. Each logger can be configured to output log contents using the console or a file.

Logback is the author of log4j framework for the development of a new generation of logging framework , it is more efficient , able to adapt to a number of operating environments , while natural support for SLF4J.

Second, SpringBoot and Logback

Assuming you use thestarterStarting the creation of a SpringBoot application will by default have imported thespring-boot-starter-logging dependency, and successively imported the dependencies needed for logback.

1. Default log format

So, when we start the SpringBoot application, the console will show INFO level log output.

As you can see, the output is as follows:

  • Date and time, accurate to the millisecond level.

  • Log level: INFO, [Log level defaults from highest to lowest: ERROR, WARN, INFO, DEBUG, TRACE].

  • Process ID

  • Separator: to identify the start of the actual log message.

  • Thread name: enclosed in square brackets (may be truncated on console output).

  • Logger name:This is usually the source class name (usually abbreviated).

  • Log messages

There is no FATAL level for logback, it corresponds to ERROR.

2. Console output

The default logging configuration is to have the log messagesDisplay to Console, by default.will be displayed above the INFO levelof the log messages. You can also set the logging information by using the--debugFlag to start debug mode.

$ java -jar  --debug

Program arguments can be edited using the IDEA operation: --debug.

Configuring debug=true also adjusts the logging level to DEBUG.

3. Document output

By default, SpringBoot's logs are only output to the console, if you still want to output to a file, you need to configure thecap (a poem)Two attributes.

The table below shows how to combinelogging.*to achieve the desired results:

Example Description
(none) (none) will only output to the console
Designation of documents (none) Write the specified log file in the current project directory
(none) Specify a directory log In the log directory under the current project, write the file

When the log file reaches 10 MB, it will trigger the scrolling policy [Slice], and by default, it will record information at the level of INFO and above. You can use the-sizeproperty changes the size limit. Unless the-historyattribute, otherwise the defaultThe last 7 days of rotation log files will be retained. It is possible to use-size-capLimits the total size of the log archive files. When the total size of the log archive exceeds this threshold, the backup is deleted. To force the log archive to be cleared at application startup, use the-history-on-startProperties.

4. Log level

You can use to set the level of all supported loggers.

  1. =warn
  2. =debug
  3. =error

5. Log groups

Use can be related to the combination of logger unified management of logging levels and other configurations. How to use it is as follows:

Assuming that group is defined astomcat

logging.group.tomcat=, , 

Once defined in this way, it is possible to configure the levels of the three loggers in question with just one line of configuration:

=TRACE

SpringBoot predefines two out-of-the-box log groups:

Name Loggers
web
sql

  1. # pre-defined
  2. =debug
  3. =debug

6. Customized log configuration

Since the logging service is generally initialized before the ApplicationContext is created, it is not necessary to control through the Spring configuration file. Therefore, through the system properties and traditional Spring Boot external configuration files can still be very good support for logging control and management.

You can choose to define the corresponding logging configuration according to your logging system by following the definition rules in the table below:

Logging System Customization
Logback , or 
Log4j2  or 
JDK (Java Util Logging)

SpringBoot's official recommendation comes with-springfile name as the configuration, e.g.rather than

The advantage of naming it this way is that because the standardThe configuration file is loaded too early, so you can't use extensions in it, you need to use the

Of course the above is the default naming rules, if you want to customize the name of the xml, custom path, you can configure through the properties:=classpath:

III. Customization considerations

Next share a configuration very detailed configuration, refer to the notes, should be able to grasp the definition of xml.

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <configuration scan="true" scanPeriod="10 seconds" debug="false">
  3. <! -- Log levels are categorized from lowest to highest as TRACE< DEBUG < INFO < WARN < ERROR < FATAL, if set to WARN, no information below WARN will be output -->
  4. <! -- scan:When this attribute is set totrueWhen the configuration file is changed, it will be reloaded, with a default value oftrue -->
  5. <! -- scanPeriod: set the time interval to monitor if the configuration file has been modified, if no time unit is given, the default unit is milliseconds. When scan istrueThis property takes effect when the The default time interval is1Minutes. -->
  6. <! -- debug:When this attribute is set totrueWhen the default value is set to 0, the logback internal log messages will be printed out to view the logback operation status in real time. The default value isfalse。 -->
  7. <contextName>logback</contextName>
  8. <! -- The value of name is the name of the variable.valuevalue when the variable is defined. The value defined by is inserted into the logger context. After defining a variable, you can make "${}" to use the variable. -->
  9. <property name="" value="log" />
  10. <property name="console_log_pattern"
  11. value="%black(%contextName-) %red(%d{yyyy-MM-dd HH:mm:ss}) %green([%thread]) %highlight(%-5level) %boldMagenta(%logger{36}) - %gray(%msg%n)"/>
  12. <property name="charset" value="UTF-8"/>
  13. <! --Output to console-->
  14. <appender name="console" class="">
  15. <! --This logging appender is for development use, only the lowest level is configured, the console outputs logging level is greater than or equal to this level of logging information-->
  16. <! -- For example, if the INFO level is configured here, logs will not be output even if the DEBUG level is configured elsewhere -->
  17. <filter class="">
  18. <level>DEBUG</level>
  19. </filter>
  20. <encoder>
  21. <pattern>${console_log_pattern}</pattern>
  22. </encoder>
  23. </appender>
  24. <! --Output to file, record only INFO level information-->
  25. <appender name="info_file" class="">
  26. <rollingPolicy class="">
  27. <fileNamePattern>${}/roll_info/logback.%d{yyyy-MM-dd}.log</fileNamePattern>
  28. </rollingPolicy>
  29. <encoder>
  30. <pattern>${console_log_pattern}</pattern>
  31. <charset>${charset}</charset>
  32. </encoder>
  33. <! -- Rolling strategy for loggers, by date, by size -->
  34. <rollingPolicy class="">
  35. <! -- Daily log archive path and format -->
  36. <fileNamePattern>${}/info/log-info-%d{yyyy-MM-dd}.%</fileNamePattern>
  37. <timeBasedFileNamingAndTriggeringPolicy class="">
  38. <maxFileSize>100MB</maxFileSize>
  39. </timeBasedFileNamingAndTriggeringPolicy>
  40. <! --Number of days log files are retained ->
  41. <maxHistory>15</maxHistory>
  42. </rollingPolicy>
  43. <! -- If more than10MB is deleted-->
  44. <triggeringPolicy class="">
  45. <maxFileSize>10MB</maxFileSize>
  46. </triggeringPolicy>
  47. <! -- This log file only records info-level -->
  48. <filter class="">
  49. <level>INFO</level>
  50. <onMatch>ACCEPT</onMatch>
  51. <onMismatch>DENY</onMismatch>
  52. </filter>
  53. </appender>
  54. <Output to file, logging only WARN level information - ! --Output to file, only WARN level information is recorded-->
  55. <appender name="warn_file" class="">
  56. </appender>
  57. <! --Output to file, log onlyERRORLevel information ->
  58. <appender name="error_file" class="">
  59. </appender>
  60. <!--
  61. The root node is mandatory and is used to specify the most basic log output level, with only one level attribute
  62. level: set the print level, case-insensitive: TRACE, DEBUG, INFO, WARN, andERROR, ALL cap (a poem)OFFThe default is DEBUG.
  63. Can contain zero or more appender elements.
  64. -->
  65. <root level="info">
  66. <appender-ref ref="console" />
  67. <appender-ref ref="info_file" />
  68. <appender-ref ref="warn_file"/>
  69. <appender-ref ref="error_file"/>
  70. </root>
  71. <!--
  72. <logger>This is used to set the log printing level for a package or a specific class, and to specify the<appender>
  73. <logger>has only one name attribute.
  74. An optional level and an optional additivity attribute.
  75. name: Specifies a package or class that is bound to this logger.
  76. level: set the print level, case-insensitive: TRACE, DEBUG, INFO, WARN, andERROR, ALL cap (a poem)OFF
  77. If this property is not set, then the current logger will inherit the level of its parent.
  78. additivity: if or not pass printing information to the parent logger, default is yes.true
  79. -->
  80. <! -- When using mybatis, sql statements are printed only under debug, and here we have only configured info, so if you want to view the sql statements, there are the following two operations:
  81. the first type of handle<root level="INFO">adapt (a story to another medium)<root level="DEBUG">This will print the sql, but then there will be a lot of other messages on the log side of things
  82. The second is a separate directory to the mapper under the DEBUG mode configuration, the code is as follows, so that the configuration of the sql statement will be printed, the other is still the normal DEBUG level:
  83. -->
  84. <logger name="" level="WARN" additivity="false">
  85. <appender-ref ref="console"/>
  86. <appender-ref ref="warn_file"/>
  87. <appender-ref ref="error_file"/>
  88. </logger>
  89. <! -- You can use springProfile if you are developing in multiple environments -->
  90. <! --Development Environment:Printing Console-->
  91. <springProfile name="dev">
  92. <! -- can output the debug logs of the project, including the mybatis sql logs -->
  93. <logger name="" level="DEBUG">
  94. <appender-ref ref="console"/>
  95. </logger>
  96. <!--
  97. The root node is mandatory and is used to specify the most basic level of logging output, with only one level attribute
  98. level: set the level of printing, case-insensitive: TRACE, DEBUG, INFO, WARN, andERROR, ALL cap (a poem)OFFThe default is DEBUG.
  99. Can contain zero or more appender elements.
  100. -->
  101. <root level="INFO">
  102. <appender-ref ref="console"/>
  103. </root>
  104. </springProfile>
  105. </configuration>

For the final result, a log file is generated in the project path:/log/info/log-info-2020-11-01., and the policy for log files is also defined in xml.

The console prints the information as shown below: