In-depth understanding of SpringBoot log framework: from entry to advanced application - (5) Detailed explanation of Log4j2 configuration file

Log4j2 official documentation: https://logging.apache.org/log4j/2.x/manual/index.html

Log4j2 is a Java logging framework for recording information about applications at runtime. It is an upgraded version of Log4j, which provides faster processing speed, faster logging and richer logging functions, and supports asynchronous logging, reducing the impact on application performance. It allows very flexible configuration and customization of logging. It is an open source project of the Apache Software Foundation and is free to use and modify.

Following are some of the main features of Log4j2:

  1. High performance: Log4j2 has excellent performance and can easily handle large amounts of log data.

  2. Flexibility: Log4j2 can be highly customized according to the needs of the application, including customizing the output format, selecting different loggers, etc.

  3. Extensibility: Log4j2 supports many extensions and can be easily integrated with other frameworks.

  4. Multi-thread safety: Log4j2 is designed with multi-thread safety in mind and can be used normally in a multi-thread environment.

  5. Configurability: Log4j2 supports multiple configuration file formats, including XML, JSON, and YAML, among others.

In short, Log4j2 is a powerful, efficient, flexible and scalable logging framework that can meet a wide range of application logging needs.

log4j2.xml configuration items

<Configuration>
  <Appenders>
    ...
  </Appenders>
  <Loggers>
    ...
  </Loggers>
  <Properties>
    ...
  </Properties>
</Configuration>

The log4j2.xml configuration file contains the following configuration items:

configuration item illustrate
Configuration Used to specify the configuration information of Log4j2, including log level, log storage location, log format, etc.
Appenders It is used to specify the destination of log output, including file, console, database, etc. Each Appender needs to specify a Layout (log format)
Loggers Used to specify the log level and Appender for each logger. You can control the log output by specifying the Logger name, level, and added Appender
Filters Used to specify filters for specific Loggers, Appenders or LogEvents, such as regular expression filtering, threshold filtering, etc.
Properties Global variables used to specify Log4j2, these variables can be used in the Log4j2 configuration file to configure some parameters
Script Used to specify a JavaScript script, allowing the script to dynamically generate log information
Custom Levels Used to define custom log levels
Include Used to introduce other XML configuration files, allowing multiple configuration files to be merged into one configuration

These configuration items can be used in combination to flexibly control the behavior of Log4j2 through configuration files.

Configuration node

The XML configuration file for Log4j2 contains the following sections:

<Configuration>
  <Appenders>
    ...
  </Appenders>
  <Loggers>
    ...
  </Loggers>
  <Properties>
    ...
  </Properties>
</Configuration>

The root element of the configuration file is <Configuration>, the following is an example of a Configuration node in Log4j2.xml:

<Configuration status="warn" monitorInterval="30">
  <!-- ... -->
</Configuration>

Among them, the status attribute specifies the level of the log, and the monitorInterval attribute specifies the time interval for monitoring log file changes. Other commonly used attributes include name, packages, shutdownHook, strict, etc. The Configuration properties of Log4j2.xml include:

Attributes illustrate
status Specifies the status of the logger, which can be "trace", "debug", "info", "warn" or "error"
monitorInterval Configuration file monitoring interval, in milliseconds
verbose Whether to display verbose logging information at startup
name Specifies the name of the log configuration file, which can be empty
packages Specify the log package that needs to be automatically configured
shutdownHook Specifies whether to use the JVM Shutdown Hook to close the logger
strict Whether to enable strict mode, if enabled, all configuration items must be configured correctly
schema Specifies the schema for the XML configuration file
advertiser Specifies the class name of the advertiser, which is used to send log records to other remote or local processes or applications

Properties variable

The Properties element in the log4j2.xml file defines a set of key-value pairs that can be used in logging. These properties can be defined in configuration files, or specified at runtime through environment variables or other means.

The following is a sample Properties element configuration:

<Properties>
   <Property name="appName">myApp</Property>
   <Property name="logDir">/var/log/myApp</Property>
</Properties>

In the above example, two properties are defined: appName and logDir. These properties can be used in logging templates as follows:

<File name="File" fileName="${logDir}/myApp.log">
   <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} %-5p ${appName} - %m%n"/>
</File>

In this example, the attributes defined by using ${appName}and are used in the logging template. ${logDir}This will be parsed into actual values ​​such as myAppand /var/log/myApp.

By using the Properties element, constant values ​​can be easily shared throughout a configuration file and easily changed at runtime.

Appender appender

Log4j2's Appender is a component used to output log messages to a specified destination. Log4j2 provides a variety of Appenders, including but not limited to:

appender type illustrate
ConsoleAppender output log messages to the console
FileAppender output log messages to a file
RollingFileAppender Output log messages to file, and support log rotation
SocketAppender Send log messages to the Socket port of the remote server
JMSAppender Send log messages to a JMS queue or topic
SMTPAppender Send logs as email
SyslogAppender Output logs to Syslog server
JDBCAppender write log to database
KafkaAppender Send log messages to Kafka topic

By configuring the Log4j2 Appender, we can output log messages to different destinations according to different requirements, which facilitates subsequent log analysis and management.

ConsoleAppender

ConsoleAppender is a logger for logging to the console. A simple example is as follows:

<Appenders>
  <Console name="Console" target="SYSTEM_OUT">
    <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
  </Console>
</Appenders>

The following are some commonly used ConsoleAppender parameters:

parameter illustrate
name Specify the name of the log outputter
target Specify the output target, such as System.out or System.err, the default is System.out
follow Specifies whether to track changes to stdout or stderr (Windows only)
encoding Specify character encoding for console output
immediateFlush Specifies whether to flush log messages to the console immediately, defaults to True

FileAppender

The following is a sample FileAppender of log4j2.xml:

<Appenders>
  <File name="FileAppender" fileName="logs/myapp.log">
    <PatternLayout pattern="%d %p %c{1.} [%t] %m%n" />
  </File>
</Appenders>

In this configuration, we defined a FileAppender and configured the output file as logs/myapp.log, which means that the log messages will all be written to logs/myapp.logthe file. We use PatternLayout to specify the output log format.

Log4j2's FileAppender has the following parameters:

parameter illustrate
name Specify the name of the Appender
fileName The save path and name of the log file. Relative and absolute paths can be used, as well as variables (${})
append Whether to append logs to the original log file, the default is true
bufferedIo Whether to enable cache writing, the default is true
bufferSize The size of the buffer, the default is 8192
immediateFlush Whether to write to the log file immediately, the default is true
layout Specifies the output format of the log file
filePermissions Specifies the permissions for the log file. Can be UNIX-style numerical permissions (such as 0644) or file permission symbols (such as rwxr-xr–)
fileOwner Specifies the owner of the log file
fileGroup Specifies the group to which the log file belongs

RollingFileAppender

RollingFileAppender is an appender used in Log4j2 to output logs to files. It can implement rolling and compression of log files to support longer log storage.

<Appenders>
  <RollingFile name="RollingFileAppender" fileName="logs/myapp.log"
               filePattern="logs/myapp-%d{yyyy-MM-dd}-%i.log.gz">
    <PatternLayout pattern="%d %p %C{1.} [%t] %m%n"/>
    <Policies>
      <TimeBasedTriggeringPolicy />
      <SizeBasedTriggeringPolicy size="100 MB" />
    </Policies>
    <DefaultRolloverStrategy max="10"/>
  </RollingFile>
</Appenders>

在这个配置中,我们定义了一个RollingFileAppender 来处理日志。它的名称是“RollingFileAppender”,它的文件名是“logs/myapp.log”,并且它的文件模式是“logs/myapp-%d{yyyy-MM-dd}-%i.log.gz”。这将导致日志文件以日期和索引进行轮换,并使用gzip进行压缩。

在RollingFileAppender中,我们使用了PatternLayout来指定日志的格式。我们还添加了两个策略,一个是TimeBasedTriggeringPolicy,它基于时间触发轮换,另一个是 SizeBasedTriggeringPolicy,它基于文件大小触发轮换。我们还指定了一个 DefaultRolloverStrategy 来定义轮换的最大文件数。

RollingFileAppender 的参数如下:

参数 说明
name 指定Appender的名称
fileName 日志文件的保存路径和名称。可以使用相对路径和绝对路径,也可以使用变量(${})
filePattern 日志文件的文件名模式,支持日期格式化。例如:logs/myapp-%d{yyyy-MM-dd}-%i.log,表示按日期划分日志文件,并使用索引号区分不同的日志文件
append 是否在原有的日志文件中追加日志,默认为true
bufferedIo 是否开启缓存写入,默认为true
bufferSize 缓冲区的大小,默认为8192
immediateFlush 是否立即写入日志文件,默认为true
layout 指定日志文件的输出格式
policy 滚动策略,支持基于时间、文件大小等方式滚动,默认为 DefaultRolloverStrategy
strategy 日志消息的格式化方式,需指定一个 Layout 实例
filter 日志过滤器,需指定一个 Filter 实例
ignoreExceptions 是否忽略错误,当写入日志文件发生错误时是否抛出异常,默认为 true

SMTPAppender

SMTPAppender是log4j2中的一个appender,它允许将日志信息通过电子邮件发送。以下是一个示例log4j2.xml配置文件中SMTPAppender发送html格式的邮件:

<Appenders>
  <SMTP name="smtpAppender" subject="Log4j2 Test Mail" to="[email protected]"
        from="[email protected]" smtpHost="smtp.gmail.com" smtpPort="587" smtpUsername="yourusername"
        smtpPassword="yourpassword" smtpProtocol="smtp" smtpDebug="true"
        htmlMsgLayout="${htmlMsgLayout}">
    <ThresholdFilter level="WARN"/>
  </SMTP>
</Appenders>
<Layouts>
  <HtmlLayout title="Log4j2 Test Mail">
    <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
  </HtmlLayout>
</Layouts>

在这个配置文件中,我们使用SMTPAppender来发送邮件。其中,我们设置了SMTP服务器的主机名、端口、用户名和密码等信息,并指定了发送的邮件内容为html格式。我们还定义了一个HtmlLayout来格式化邮件内容,它将普通的日志信息格式化为html形式。

在实际使用中,只需将to和from设置为你的邮箱地址,以及填写正确的smtpHost、smtpPort、smtpUsername和smtpPassword即可成功发送一封带有html格式的邮件。

以下是SMTPAppender的属性:

参数 说明
name Appender的名称
to 指定邮件接收者的电子邮件地址
cc 指定邮件抄送者的电子邮件地址
bcc 指定邮件密送者的电子邮件地址
from 指定邮件发送者的电子邮件地址
smtpHost SMTP服务器的主机名或IP地址
smtpPort SMTP服务器的端口号,默认为25
smtpUsername SMTP服务器的用户名
smtpPassword SMTP服务器的密码
smtpProtocol SMTP服务器的协议,默认为smtp
bufferSize 缓冲区大小,默认为512
subject 邮件主题,默认为Log4j Log Message
layout 指定日志信息的格式
filter 指定日志信息的过滤器
ignoreExceptions 是否忽略异常,默认为true。如果设置为false,则发生异常时邮件发送将会失败。

以上是 SMTPAppender 的属性,可以根据需要进行配置。

Loggers 日志记录器

log4j2.xml文件中的loggers元素定义了日志记录器的配置。它包含一个或多个logger元素,每个logger元素代表一个具体的日志记录器。每个logger元素可以指定日志级别、日志输出目标(appender)、日志过滤器(filter)等。

以下是一个示例loggers元素的配置:

<Loggers>
    <Logger name="com.example" level="info" additivity="false">
        <AppenderRef ref="CONSOLE" />
        <AppenderRef ref="FILE" />
    </Logger>
    <Root level="error">
        <AppenderRef ref="CONSOLE" />
        <AppenderRef ref="FILE" />
    </Root>
</Loggers>

在上面的示例中,有两个 logger 元素。第一个 logger 元素的 name 属性为“com.example”,表示这是一个名为“com.example”的日志记录器。它的 level 属性为“info”,指定日志级别为“info”级别。additivity 属性为“false”,表示在这个日志记录器中,日志不会被发送到它的父级日志记录器中。

第二个 logger 元素是 root 元素,表示所有未被明确指定日志记录器的日志都会被记录到这个 root 记录器中。它的 level 属性为“error”级别。

两个 logger 元素都引用了两个 appender(CONSOLE 和 FILE),这表示日志会被输出到控制台和文件中。

Filters 过滤器

log4j2.xml 中的 Filters 指的是过滤器,可以帮助我们过滤掉不需要的日志。Filters可以被配置在 Logger、Appender、Layout 等组件中。常用的 Filters 有以下几种:

过滤器 说明
ThresholdFilter 根据日志级别过滤,比如只输出ERROR级别及以上的日志
RegexFilter 根据正则表达式过滤,比如只输出满足特定正则表达式的日志
MapFilter 根据键值对过滤,比如只输出包含特定键值对的日志
StructuredDataFilter 根据结构化数据过滤,比如只输出带有指定结构化数据的日志

Filters 可以被链式组合起来,以实现更复杂的过滤逻辑。例如,可以使用 ThreadContextMapFilter 过滤指定键值对,然后再使用 ThresholdFilter 过滤指定级别的日志事件。

可以在 log4j2.xml 文件中通<Filters>标签中添加一个或多个Filters。例如:

<Appenders>
  <Console name="ConsoleAppender" target="SYSTEM_OUT">
    <ThresholdFilter level="WARN" onMatch="DENY" onMismatch="NEUTRAL"/>
    <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
  </Console>
</Appenders>

该配置文件将所有级别为WARN及以上的日志事件过滤掉,并将其输出到控制台。其中,onMatch 和 onMismatch 表示匹配和不匹配时的处理方式,可以取值为DENY(拒绝)、NEUTRAL(中立)和ACCEPT(接受)。

Layout 输出格式

Log4j2的Layout是用于指定日志消息输出格式的组件。它定义了日志事件的消息格式,以便它可以被写入到指定的输出目标中。

Log4j2提供了多种Layout实现,包括:

LayoutType 说明
PatternLayout 通过指定一个格式化字符串来输出日志消息。
HtmlLayout 用HTML标记格式化日志消息,使其在网页上更容易查看。
XmlLayout 以XML格式输出日志事件。
CsvLayout 以逗号分隔的格式输出日志消息,方便导入到Excel等表格软件中。
JsonLayout 以JSON格式输出日志事件。

用户可以根据需要选择合适的Layout实现,并根据自己的需求进行配置和定制化。例如,可以通过设置Layout的属性来控制时间和日期格式、输出日志级别等信息。

Log4j2-spring.xml 样例

下面是一个示例的 log4j2.xml 配置文件,其中包含了按大小滚动的设置,以及控制日志输出的配置选项:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Appenders>
        <!-- Size-based rolling policy -->
        <RollingFile name="SizeBasedRollingFileAppender" fileName="logs/app.log" filePattern="logs/app-%d{yyyy-MM-dd}-%i.log" >
            <ThresholdFilter level="INFO" onMatch="ACCEPT" onMismatch="DENY"/>
            <PatternLayout>
                <pattern>%d %p %c{1.} [%t] %m%n</pattern>
            </PatternLayout>
            <Policies>
                <SizeBasedTriggeringPolicy size="10 MB"/>
            </Policies>
            <DefaultRolloverStrategy max="10"/>
        </RollingFile>

        <!-- Console appender -->
        <Console name="ConsoleAppender" target="SYSTEM_OUT">
            <PatternLayout>
                <pattern>%d %p %c{1.} [%t] %m%n</pattern>
            </PatternLayout>
        </Console>
        
    </Appenders>
    <Loggers>
        <!-- Root logger -->
        <Root level="INFO">
            <AppenderRef ref="SizeBasedRollingFileAppender" />
            <AppenderRef ref="ConsoleAppender" />
        </Root>
    </Loggers>
</Configuration>

Guess you like

Origin blog.csdn.net/qq_20185737/article/details/131252893