Logback.xml detailed configuration

Log4j or LogBack is recommended for SpringBoot projects because logging is essential for locating and resolving problems.

Generally logback is used a little bit more, and it’s more flexible.

A lot of times when I’m configuring logback, I take an XML from somewhere else and change it, and as time goes on, I forget a lot of the configuration, so I’ll summarize it today.

logback-spring.xml

So the first row is 1, 2, 3

<? The XML version = "1.0" encoding = "utf-8"? >

This one is simple: declare the XML file and encoding format.

Let’s get down to business.

configuration

The Logback configuration is packaged in a < Configuration > TAB.

<configuration scan='true' scanPeriod="60 seconds" debug="false">

  • scan: in order totrueThe configuration file has been changed and will be reloaded. Default istrue
  • scanPeriod: Indicates the interval at which the configuration file is modified. The default unit is milliseconds
  • debug: print outlogbackInternal logs, defaultfalse

These can be declared as:

  • springProperty
  • property
  • conversionRule
  • appender
  • root
  • logger
  • springProfile

springProperty

Properties can be obtained from the application.properties configuration file.

Like this,

<springProperty scope="context" name="LOG_PATH" source="logging.path"/>

  • scope: scope
  • name: name, the name when referenced below
  • sourceIn:application.propertiesIn the filekey
  • defaultValue: The default value, this property inapplication.propertiesIf this parameter is not set, the default value is used

property

${name} can be used to refer to value

<property name="LOG_PATTERN" value="%d{yyyy-MM-dd HH:mm:ss} [%p] [%.10t] [%c{1}][%L] %X{traceId} %m%n" />

conversionRule

It is mainly used to configure converters. You can customize Pattern templates, or introduce some other templates to resolve Pattern, such as printing color logs and printing IP addresses.

Print color log converter.

<conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter" />

  • conversionWordIn:PatternThe keyword in
  • converterClass: converter class

<property name="COLOR_LOG_PATTERN" value="%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(%p) %clr(${PID}){magenta} %clr([%.10t]){yellow} %clr([%c{1}]){blue}%clr([%L]){faint}%X{traceId} %m%n"/>

Above % CLR is to use ColorConverter to parse, after {blue} is to display the color.

Color effect:

The Pattern expression

  • %d: indicates the printing time of the output log, and the syntax of the modejava.text.SimpleDateFormatCompatible (D /date)
  • %p: output log level (P/LE/level)
  • ${PID} : outputs the process Id
  • %.10t: outputs the name of the thread that generates logs. (t/thread)
  • %c{1} : name of the logger that outputs the log (c/LO/logger)
  • %L: Line number of output execution log request (L/line)
  • %X: NDC(nested diagnostic environment) associated with the current thread, trace Id, used by MDC
  • %m: Output information provided by the application, detailed log (m/MSG/message)
  • % n: a newline

There are a few others that are not commonly used:

  • C/class: outputs the fully qualified name of the caller that executes the record request. Like C, avoid using such as %C{5}.
  • ContextName/cn: output contextName.
  • F/file: Outputs the Java source file name of the execution record request. Try to avoid it.
  • Caller {depth} : Displays the location of the caller whose logs are generated. The integer option indicates the depth of the output. For example, % caller {2}
  • M/method: indicates the method name of the log execution request. Try to avoid it.
  • R/relative: Outputs the time, in milliseconds, from the start of the program to the creation of a log record.
  • Replace (p){r, t} : p is the log content, and r is the regular expression. Replace the content matching r in P with T. For example: “%replace(% MSG){‘\s’, ”}”

After the configuration caller

Format character

  • Left-aligned modifier (-) : This is followed by the optional minimum width modifier, expressed as a decimal number. If the character is smaller than the minimum width, it is left or right, left (that is, right-aligned) by default, and the padding is a space. If the character is larger than the minimum width, the character is never truncated.
  • Maximum width modifier (.) : followed by a decimal number. If the character is larger than the maximum width, it is truncated from the front. After the “-” to add a number, indicating truncation from the tail.

appender

The logging component has two required properties name and class. Name specifies the customizable name of the appender, and class specifies the fully qualified name of the appender.

Console printing:

<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
        <pattern>${COLOR_LOG_PATTERN}</pattern>
        <charset>utf-8</charset>
    </encoder>
</appender>
Copy the code
  • Pattern: Sets the print format
  • Charset: Encoding format

Print to file

<appender name="xxxx" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>${LOG_PATH}/xxxx.log</file>
    <encoder>
        <pattern>${LOG_PATTERN1}</pattern>
        <charset>utf-8</charset>
    </encoder>
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        <fileNamePattern>${LOG_PATH}/xxxx.log.%d{yyyy-MM-dd}.gz</fileNamePattern>
        <maxHistory>15</maxHistory>
    </rollingPolicy>
</appender>
Copy the code
  • Ch. Qos. Logback. Core. Rolling. RollingFileAppender: rolling log
  • File: indicates the path and name of the log file to be written. If the log file does not exist, create a new one
  • Encoder: Sets the encoding
    • Pattern: Indicates the log printing format
    • Charset: Encoding format
  • RollingPolicy:ch.qos.logback.core.rolling.TimeBasedRollingPolicySet scroll policy to save by time
  • FileNamePattern: indicates the log namegzThe end is automatically compressed.
  • MaxHistory: indicates the maximum number of days for which logs are saved. Logs generated before this number are automatically deleted.

Appender can also configure the ch.qos.logback.classic.net.SMTPAppender, when an exception occurs, you can send mail, and ch. Qos. Logback. Classic. Db. DBAppender, can keep the log into the database.

root

<root level="INFO">
    <appender-ref ref="console"/>
    <appender-ref ref="xxxx"/>
</root>
Copy the code
  • Root: YesloggerYou can set the log output level. The default isDEBUG. It’s also a Logger, but only with the Level attribute.
  • Appender-ref: Logs are printed to the console and log files.

logger

<logger name="com.ler.yshi.interceptor.PrintSqlInterceptor" level="logger_dao_level" additivity="false">
    <appender-ref ref="console"/>
    <appender-ref ref="xxxx"/>
    <appender-ref ref="sql"/>
</logger>
Copy the code
  • Logger: Used to set the log level for a package or a specific class.
  • Name: used to specify thisloggerA package of constraints or a specific class,com.ler.yshi.interceptor.PrintSqlInterceptorThis class is the interceptor from which I print the full SQL.
  • Level: indicates the log level
  • Addtivity: Whether or not upwardloggerPass print information. The default is true
  • Appender – ref:
    • loggerIt can contain zero or more elements to identify thisappenderWill be added to thislogger. The idea here is thatPrintSqlInterceptortheSQLLogs are printed to the console, log files, andSQLIn the log file

springProfile

Spring profiles can also be used in logback.xml to configure different logging for multiple environments.

<! -- Development environment log level is DEBUG -->
<springProfile name="dev">
    <root level="DEBUG">
        <appender-ref ref="FILE"/>
        <appender-ref ref="STDOUT"/>
    </root>
</springProfile>

<! -- Test environment log level is INFO -->
<springProfile name="test">
    <root level="INFO">
        <appender-ref ref="FILE"/>
        <appender-ref ref="STDOUT"/>
    </root>
</springProfile>
Copy the code

But we don’t use this very much.

Logback knows that, and it’s basically fine to use it, and there are some complicated ones, but they don’t have to be complicated.

Well, finally welcome everyone to pay attention to my public number, learn together, progress together. Refueling 🤣

Nanzhao Blog

reference

Blog.csdn.net/snail_bi/ar… www.cnblogs.com/cb0327/p/57…