Spring boot (x) logback and log4j2 integration and log development history

1、 Introduction

There are many well-known logs in Java, such as Jul, log4j, JCL, slf4j, logback and log4j2. What is the relationship between these log frameworks? The reason for its birth is to solve what problems? Let's take a look.

1.1 JUL

Java has its own logging framework Jul (Java util logging). Under java.util.logging, few developers use it because it is not friendly to developers, the use cost is too high and the log level classification is not clear.

1.2 Log4j

Because of the defects of Jul, this gives log4j an opportunity. Once launched, all log4j quickly become popular all over the world.

1.3 JCL

JCL is the abbreviation of Jakarta commons logging. Jakarta here refers to an organization, not Jakarta, the capital of India. Jakarta, an early Apache open source project, is used to manage various Java subprojects, such as tomcat, ant, maven, struts, JMeter, velocity, commons, etc. In December 2011, after all subprojects were migrated to stand-alone projects, the Jakarta name was no longer used.

The original intention of JCL is that some packages of Java use Jul, and many log4j users use it. JCL provides a set of APIs to switch between different loggers.

1.4 SLF4J

Slf4j (simple logging facade for Java) is a simple logging facade, which has similar functions to JCL, but JCL has a fatal disadvantage that the algorithm is complex and it is difficult to eliminate problems. Slf4j was born to solve the shortcomings of JCL.

It is worth mentioning that the author of slf4j is the author of log4j.

1.5 Logback

Logback is another open-source log component of the author of log4j. Compared with log4j, logback has rebuilt the kernel, which improves its performance a lot, about 10 times that of log4j. At the same time, it occupies less memory, and fully implements the slf4j API, which is a convenient way for you to switch the log framework.

1.6 Log4j2

Log4j2 has the same functions as logback, but it also has its own functions, such as plug-in structure, configuration file optimization, asynchronous log, etc.

Log4j2 is an upgrade of log4j, which is 1.5% higher than its predecessor log4j X provides significant improvements and many of the improvements available in logback, while fixing some inherent problems in the logback architecture.

Judging from the update log of GitHub, logback has not been updated for half a year, while the update of log4j2 under Apache, a well-known organization, is very active, log4j 1 X stopped maintenance and updating in August 2015.

GitHub address

Logback: https://github.com/qos-ch/logback

log4j2: https://github.com/apache/logging-log4j2

This article looks at the implementation of logback and log4j2 in spring boot.

2、 Logback usage

development environment

2.1 use of logback

Spring boot integrates logback by default and can be used out of the box, which is very convenient. Because spring boot starter logging is the logging implementation of logback, and spring boot starter, the spring boot startup item, relies on spring boot starter logging, spring boot integrates logback by default. The package dependency is shown in the following figure:

Logs are output from the default console. We use logback when the program starts, as shown in the following figure:

Interpretation of log composition:

2.2 input file

If you need to output the log to a file, you only need to use the application Properties configuration file setting: logging File or logging Path, for example:

logging.level.root=info
logging.file=D:\\log\\my.log

You can ignore lower level log output by setting the log level.

Note: logging File and logging You can set a property of path. If both are set, you can use logging File, logging Invalid path.

Log file capacity setting: use the "logging.file.max-history" attribute to set the maximum log capacity. If it exceeds 10m by default, it will be divided into multiple files.

2.3 user defined log configuration

The log service is initialized before the ApplicationContext is created, so logs can be managed and controlled by setting properties and traditional configuration XML files.

Just create an XML file with agreed names under Src / main / resources to complete the setting of the log system. Different log systems have different agreed names, as shown in the following list:

Spring boot officials suggest using the naming rule of "- Spring" for log configuration, such as logback spring XML instead of logback xml。

Of course, you can also customize the log name, just in application Properties can be configured. The code is as follows:

Take a look at logback spring XML sample file:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

    <!-- 日志根目录-->
    <springProperty scope="context" name="LOG_HOME" source="logging.path" defaultValue="/data/logs/spring-boot-logback"/>

    <!-- 日志级别 -->
    <springProperty scope="context" name="LOG_ROOT_LEVEL" source="logging.level.root" defaultValue="DEBUG"/>

    <!--  标识这个"STDOUT" 将会添加到这个logger -->
    <springProperty scope="context" name="STDOUT" source="log.stdout" defaultValue="STDOUT"/>

    <!-- 日志文件名称-->
    <property name="LOG_PREFIX" value="spring-boot-logback" />

    <!-- 日志文件编码-->
    <property name="LOG_CHARSET" value="UTF-8" />

    <!-- 日志文件路径+日期-->
    <property name="LOG_DIR" value="${LOG_HOME}/%d{yyyyMMdd}" />

    <!--对日志进行格式化-->
    <property name="LOG_MSG" value="- | [%X{requestUUID}] | [%d{yyyyMMdd HH:mm:ss.SSS}] | [%level] | [${HOSTNAME}] | [%thread] | [%logger{36}] | --> %msg|%n "/>

    <!--文件大小,默认10MB-->
    <property name="MAX_FILE_SIZE" value="50MB" />

    <!-- 配置日志的滚动时间 ,表示只保留最近 10 天的日志-->
    <property name="MAX_HISTORY" value="10"/>

    <!--输出到控制台-->
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <!-- 输出的日志内容格式化-->
        <layout class="ch.qos.logback.classic.PatternLayout">
            <pattern>${LOG_MSG}</pattern>
        </layout>
    </appender>

    <!--输出到文件-->
    <appender name="0" class="ch.qos.logback.core.rolling.RollingFileAppender">
    </appender>

    <!-- 定义 ALL 日志的输出方式:-->
    <appender name="FILE_ALL" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <!--日志文件路径,日志文件名称-->
        <File>${LOG_HOME}/all_${LOG_PREFIX}.log</File>

        <!-- 设置滚动策略,当天的日志大小超过 ${MAX_FILE_SIZE} 文件大小时候,新的内容写入新的文件, 默认10MB -->
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">

            <!--日志文件路径,新的 ALL 日志文件名称,“ i ” 是个变量 -->
            <FileNamePattern>${LOG_DIR}/all_${LOG_PREFIX}%i.log</FileNamePattern>

            <!-- 配置日志的滚动时间 ,表示只保留最近 10 天的日志-->
            <MaxHistory>${MAX_HISTORY}</MaxHistory>

            <!--当天的日志大小超过 ${MAX_FILE_SIZE} 文件大小时候,新的内容写入新的文件, 默认10MB-->
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>${MAX_FILE_SIZE}</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>

        </rollingPolicy>

        <!-- 输出的日志内容格式化-->
        <layout class="ch.qos.logback.classic.PatternLayout">
            <pattern>${LOG_MSG}</pattern>
        </layout>
    </appender>

    <!-- 定义 ERROR 日志的输出方式:-->
    <appender name="FILE_ERROR" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <!-- 下面为配置只输出error级别的日志 -->
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>ERROR</level>
            <OnMismatch>DENY</OnMismatch>
            <OnMatch>ACCEPT</OnMatch>
        </filter>
        <!--日志文件路径,日志文件名称-->
        <File>${LOG_HOME}/err_${LOG_PREFIX}.log</File>

        <!-- 设置滚动策略,当天的日志大小超过 ${MAX_FILE_SIZE} 文件大小时候,新的内容写入新的文件, 默认10MB -->
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">

            <!--日志文件路径,新的 ERR 日志文件名称,“ i ” 是个变量 -->
            <FileNamePattern>${LOG_DIR}/err_${LOG_PREFIX}%i.log</FileNamePattern>

            <!-- 配置日志的滚动时间 ,表示只保留最近 10 天的日志-->
            <MaxHistory>${MAX_HISTORY}</MaxHistory>

            <!--当天的日志大小超过 ${MAX_FILE_SIZE} 文件大小时候,新的内容写入新的文件, 默认10MB-->
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>${MAX_FILE_SIZE}</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>

        <!-- 输出的日志内容格式化-->
        <layout class="ch.qos.logback.classic.PatternLayout">
            <Pattern>${LOG_MSG}</Pattern>
        </layout>
    </appender>

    <!-- additivity 设为false,则logger内容不附加至root ,配置以配置包下的所有类的日志的打印,级别是 ERROR-->

    <logger name="org.springframework"     level="ERROR" />
    <logger name="org.apache.commons"      level="ERROR" />
    <logger name="org.apache.zookeeper"    level="ERROR"  />
    <logger name="com.alibaba.dubbo.monitor" level="ERROR"/>
    <logger name="com.alibaba.dubbo.remoting" level="ERROR" />

    <!-- ${LOG_ROOT_LEVEL} 日志级别 -->
    <root level="${LOG_ROOT_LEVEL}">

        <!-- 标识这个"${STDOUT}"将会添加到这个logger -->
        <appender-ref ref="${STDOUT}"/>

        <!-- FILE_ALL 日志输出添加到 logger -->
        <appender-ref ref="FILE_ALL"/>

        <!-- FILE_ERROR 日志输出添加到 logger -->
        <appender-ref ref="FILE_ERROR"/>
    </root>

</configuration>

2.4 using logs in code

To use logs in code, you only need to use the following code:

private Logger logger = LoggerFactory.getLogger(this.getClass());
//...
logger.debug("this is debug");
logger.info("this is info");

3、 Log4j2 integration

3.1 configuring dependent components

When adding log4j2 dependency to spring boot, you need to exclude logback dependency and configure POM The XML code is as follows:

<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
			<exclusions><!-- 去掉logback配置 -->
				<exclusion>
					<groupId>org.springframework.boot</groupId>
					<artifactId>spring-boot-starter-logging</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		
		<dependency> <!-- 引入log4j2依赖 -->
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-log4j2</artifactId>
		</dependency>
</dependencies>

3.2 user defined log configuration

Add log4j2 spring The XML file is under Src / main / resources, and the configuration file code is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
	<Appenders>
		<Console name="CONSOLE" target="SYstem_OUT">
			<PatternLayout charset="UTF-8" pattern="[%-5p] %d %c - %m%n" />
		</Console>

		<File name="File" fileName="D:\\mylog.log">
			<PatternLayout pattern="%m%n" />
		</File>
	</Appenders>

	<Loggers>
		<root level="info">
			<AppenderRef ref="CONSOLE" />
			<AppenderRef ref="File" />
		</root>
	</Loggers>
</configuration>

Enter the log to the console and disk D mylog Log file.

So far, the integration of log4j2 has been completed. Run the project and view the log.

Sample source code: https://github.com/vipstone/springboot-example/tree/master/springboot-logging

reference material

Past and present life of Java log: https://www.cnblogs.com/xiexj/p/9417128.html

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>