Akik God loves apples

cnblogs.com/keeya/p/10101547.html

If the first thing we did was build the Spring framework, then the second thing we did was build a logging framework on top of Sring. I think many of you know the importance of logging for a project, especially an online Web project, because logging is probably the only way we know how the application is performing.

In the context of 18 years, more and more enterprises are using Springboot and Springcloud to build their enterprise microservices projects. This article is a summary of the blogger’s practice of integrating Log4j2 logs with Springboot.

Common Logging frameworks

  • Java.util. logging: Java native logging framework introduced in JDK 1.4

  • Log4j: An open source project of Apache that controls the destination of log messages to the console, files, GUI components, and so on, and controls the output format of each log message. These can be flexibly configured through a configuration file without modifying application code. Although maintenance has been discontinued, log4j is now used by most enterprises.

  • LogBack: is an improved version of Log4j

  • Log4j2: Log4j2 is not just an upgraded version of Log4j, it has been rewritten from scratch

Log facade SLF4J

The above describes some logging framework implementations, where we need a logging facade to address the coupling between the system and the logging implementation framework. SLF4J, Simple Logging Facade for Java, is not really a Logging implementation but a abstraction layer that allows you to use any Logging implementation in the background.

As with the previous logging frameworks, each logging framework has its own API, and using the corresponding framework requires using its own API, which greatly increases the coupling of application code to the logging framework.

With SLF4J, applications can go live without changing a single line of code, no matter how the underlying logging framework changes.

Why log base 4j2

Compared with other log systems, log4j2 loses less data. Disruptor technology provides 10 times better performance than logBack and others in multi-threaded environments; The concurrency feature of JDK1.5 is used to reduce the occurrence of deadlocks.

Here are some performance reviews from other posts on the web:

  • You can see that Logback performance is worst in synchronous logging mode.

  • Log4j2 performs best in both synchronous and asynchronous log mode.

The reason for the superior performance of log4j2 is that log4j2 uses LMAX, a lock-free library for interthread communication, instead of the queues used by LogBack and Log4j. Concurrency performance is greatly improved.

Integration steps

The introduction of the Jar package

By default, SpringBoot uses the logback logging framework, so you need to exclude logback. Otherwise, jar dependency conflicts will occur.

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions><! --> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <! - the introduction oflogGroupId >org.springframework.boot</groupId> <artifactId>spring-boot-starter-log4j2</artifactId> </dependency>Copy the code

The configuration file

If you customize the file name, you need to configure it in application.yml

logging:  config: xxxx.xml  level:    cn.jay.repository: traceCopy the code

The default is log4j2-spring. XML, which saves the configuration in application.yml

Configuration file template

Log4j uses a.properties file as its main configuration file, whereas log4j2 has abandoned this method in favor of.xml,.json, or.jsn. Because the properties file is really a bit bad to read. Here is a template for bloggers to match for your reference.

<? xml version="1.0" encoding="UTF-8"? > <! -- Status after Configuration, this is used for Settingslog4j2's own internal output, you don't have to set it, but when you set it to trace, you'll see thatlog4j2 internal various verbose output --><! --monitorInterval: Log4j can automatically detect changes to configuration files and reconfiguration itself, set the interval of seconds -->< Configuration monitorInterval="5"> <! -- Log levels and priorities: OFF > FATAL > ERROR > WARN > INFO > DEBUG > TRACE > ALL --> <! -- Variable configuration --> <Properties> <! Format output: %date indicates the date, %thread indicates the thread name, %-5level indicates the level from the left 5 character width % MSG: log message, %n is a newline character --> <! -- %logger{36} Indicates a maximum of 36 characters for logger names --> <property name="LOG_PATTERN" value="%date{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n"/ > <! -- Define log store path, do not configure relative path --> <property name="FILE_PATH" value="Change to your log path." />    <property name="FILE_NAME" value="Change to your project name." />  </Properties>  <appenders>    <console name="Console" target="SYSTEM_OUT"> <! PatternLayout Pattern = --> <PatternLayout pattern="${LOG_PATTERN}"/ > <! -- The console outputs only messages of level or higher (onMatch). The other messages are rejected (onMismatch) --> <ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/> </console> <! -- The file will print out all the information, thislogThe program is automatically cleared each time it is run, as determined by the append property, suitable for temporary testing --> <File name="Filelog" fileName="${FILE_PATH}/test.log" append="false">      <PatternLayout pattern="${LOG_PATTERN}"/> </File> <! <RollingFile name= > <RollingFile name= > <RollingFile name= > <RollingFile name= > <RollingFile name= > <RollingFile name= > <RollingFile name= > <RollingFile name= > <RollingFile name= > <RollingFile name= > <RollingFile name="RollingFileInfo" fileName="${FILE_PATH}/info.log" filePattern="${FILE_PATH}/${FILE_NAME}-INFO-%d{yyyy-MM-dd}_%i.log.gz"> <! -- The console outputs only messages of level or higher (onMatch). The other messages are rejected (onMismatch) --> <ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/>      <PatternLayout pattern="${LOG_PATTERN}"/> <Policies> <! - the interval attribute is used to specify how long scroll, the default is 1 hour - > < TimeBasedTriggeringPolicy interval ="1"/>        <SizeBasedTriggeringPolicy size="10MB"/> </Policies> <! -- DefaultRolloverStrategy if not set, default to start overwriting a maximum of 7 files in the same folder --> <DefaultRolloverStrategy Max ="15"/> </RollingFile> <! -- This will print all logs of warn and below levels. Every time the log size exceeds size, it will be automatically stored in a folder created by year and month and compressed for archiving --> <RollingFile name="RollingFileWarn" fileName="${FILE_PATH}/warn.log" filePattern="${FILE_PATH}/${FILE_NAME}-WARN-%d{yyyy-MM-dd}_%i.log.gz"> <! -- The console outputs only messages of level or higher (onMatch). The other messages are rejected (onMismatch) --> <ThresholdFilter level="warn" onMatch="ACCEPT" onMismatch="DENY"/>      <PatternLayout pattern="${LOG_PATTERN}"/> <Policies> <! - the interval attribute is used to specify how long scroll, the default is 1 hour - > < TimeBasedTriggeringPolicy interval ="1"/>        <SizeBasedTriggeringPolicy size="10MB"/> </Policies> <! -- DefaultRolloverStrategy if not set, default to start overwriting a maximum of 7 files in the same folder --> <DefaultRolloverStrategy Max ="15"/> </RollingFile> <! <RollingFile name= <RollingFile name= <RollingFile name= <RollingFile name= <RollingFile name= <RollingFile name= <RollingFile name= <RollingFile name= <RollingFile name= <RollingFile name= <RollingFile name="RollingFileError" fileName="${FILE_PATH}/error.log" filePattern="${FILE_PATH}/${FILE_NAME}-ERROR-%d{yyyy-MM-dd}_%i.log.gz"> <! -- The console outputs only messages of level or higher (onMatch). The other messages are rejected (onMismatch) --> <ThresholdFilter level="error" onMatch="ACCEPT" onMismatch="DENY"/>      <PatternLayout pattern="${LOG_PATTERN}"/> <Policies> <! - the interval attribute is used to specify how long scroll, the default is 1 hour - > < TimeBasedTriggeringPolicy interval ="1"/>        <SizeBasedTriggeringPolicy size="10MB"/> </Policies> <! -- DefaultRolloverStrategy if not set, default to start overwriting a maximum of 7 files in the same folder --> <DefaultRolloverStrategy Max ="15"/> </RollingFile> </appenders> <! Logger nodes are used to specify log forms separately, such as different log levels for classes under specified packages. -- > <! Loggers > <loggers> <! -- Filter out spring and Mybatis DEBUG messages --> < Logger name="org.mybatis" level="info" additivity="false">      <AppenderRef ref="Console"/> </logger> <! -- Monitor system information --> <! If additivity is set tofalse, the child Logger will output only in its own appender and not in the parent Logger's appender. --> <Logger name="org.springframework" level="info" additivity="false">      <AppenderRef ref="Console"/>    </Logger>    <root level="info">      <appender-ref ref="Console"/>      <appender-ref ref="Filelog"/>      <appender-ref ref="RollingFileInfo"/>      <appender-ref ref="RollingFileWarn"/>      <appender-ref ref="RollingFileError"/>    </root>  </loggers></configuration>Copy the code

Configuration Parameters overview

This section describes common configuration parameters

The level of logging

Mechanism: If the level of a log message is greater than or equal to that of the configuration file, the log message is recorded.

You can write a trace output to debug, which is generally used as the lowest level. Trace is rarely used. Info: Outputs important information. Warn is used more often. Some of the information is not error, but it should also give some prompts to the programmer. Error: indicates an error message. They use it a lot. Fatal: fatal error.

The output source

CONSOLE (output to CONSOLE) FILE (output to FILE)

format

SimpleLayout: Display HTMLLayout in a simple form: Display HTMLLayout in an HTML table PatternLayout: Display custom log layout:

%d{YYYY-MM-DD HH: MM :ss, SSS} : indicates the time when the log is generated and the output time is in milliseconds. %-5level: indicates the log output level. -5 indicates the left aligned and the output is fixed with five characters. Output the current thread name %p: log output format %m: log content, that is, logger.info("message")%n: newline character %C: Java class name (%F)%L: line number %M: method name %L: line number of the output statement, including class name, method name, file name, and line number hostName: local machine name hostAddress: local IP addressCopy the code

Log4j2 Configuration details

The root node Configuration

There are two properties:

  • status

  • monitorinterval

There are two child nodes:

  • Appenders

  • Loggers(indicating that multiple appenders and Loggers can be defined).

The status command is used to specify the level of log4j’s own printed logs.

Monitorinterval Specifies the monitoring interval that log4J automatically reconfigures, in seconds, minimum 5s.

Appenders node

There are three common sub-nodes :Console, RollingFile, and File

The Console node defines the Appender for output to the Console.

Name: Appender name target:SYSTEM_OUT or SYSTEM_ERR, default: system_out.patternLayout: output format, default :%m%n

The File node is used to define the Appender for the output File to the specified location.

FileName: specifies the name of the destination log file with the full path. PatternLayout: Output format, not set Default :%m%n.

The RollingFile node is used to define new appenders that automatically delete old ones when the specified criteria are exceeded.

FileName: specifies the name of the destination log file with the full path. PatternLayout: Output format, not set Default :%m% N. filePattern: Specifies the file transfer and rename rules when Rolling occurs. Policies: Specifies the rolling log policy, that is, when to create a log file and export logs. TimeBasedTriggeringPolicy: Policies child nodes, rolling strategy based on time, the interval attribute is used to specify how long scroll, the default is 1 hour. Ulate = True modulate= True modulate= True modulate=true modulate=true modulate= True Rather than 7 am. SizeBasedTriggeringPolicy: Policies child nodes, rolling strategy based on the specified file size, the size attribute is used to define the size of each log file. DefaultRolloverStrategy: Used to specify the maximum number of log files in a folder to start deleting the oldest and creating new ones (via the Max attribute).

Loggers node

There are two common types :Root and Logger.

The Root node is used to specify the Root log for the project. If Logger is not specified separately, the Root log output is used by default

Level: indicates the log output level. There are eight levels in ascending order: All < Trace < Debug < Info < Warn < Error < AppenderRef: The Root appender. Logger node is used to specify the log format separately, for example, to specify different log levels for classes under specified packages. Level: indicates the log output level. There are eight log output levels in ascending order: All < Trace < Debug < Info < Warn < Error < Fatal < off. name: specifies the class to which the Logger belongs or the package path to which the class belongs, inherited from the Root node. AppenderRef: Logger’s child node that specifies to which Appender the log should be exported. If this is not specified, it inherits from Root by default. If specified, it will output in both the specified Appender and Root’s Appender, and we can set Logger additivity=”false” to output only in our custom Appender. Simple to use

Simple to use

public class LogExampleOther {  private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(LogExampleOther.class);  public static void main(String... args) {    log.error("Something else is wrong here");  }}Copy the code

Use lombok tools to simplify the creation of Logger classes

Lombok is a jar of annotation tools that can help you skip a lot of code. Reference:

https://www.cnblogs.com/keeya/p/9929617.html

Using Lombok, the following code is equivalent to the above code to make logging easier.

@Slf4jpublic class LogExampleOther {  public static void main(String... args) {    log.error("Something else is wrong here");  }}Copy the code

Refer to the article

https://mp.weixin.qq.com/s/vCixKVXys5nTTcQQnzrs3w

https://blog.csdn.net/yjh1271845364/article/details/70888262