Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use log4j2 logs in Springboot

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces "how to use log4j2 log in Springboot" related knowledge, editor through the actual case to show you the operation process, the method of operation is simple and fast, practical, I hope that this "how to use log4j2 log in Springboot" article can help you solve the problem.

Common log framework

Java.util.logging: Java native logging framework introduced by JDK in version 1.4

Log4j:Apache is an open source project that can control the transmission of log information to the console, files, GUI components, etc., and can control the output format of each log, which can be flexibly configured through a configuration file without the need to modify the application code. Although maintenance has been stopped, most enterprises use log4j at present.

LogBack: an improved version of Log4j

Log4j2:Log4j2 is no longer just an upgraded version of Log4j, it has been rewritten from beginning to end

Log facade slf4j

The above introduction is the implementation of some logging framework, here we need to use the log facade to solve the coupling between the system and the log implementation framework. SLF4J, or simple logging facade (Simple Logging Facade for Java), is not a real logging implementation, but an abstraction layer that allows you to use any logging implementation in the background.

Like the previous several logging frameworks, each logging framework has its own separate API. To use the corresponding framework, it is necessary to use its corresponding API, which greatly increases the coupling of application code to the logging framework.

After using slf4j, for the application, no matter how the underlying logging framework changes, the application does not need to modify any line of code to go online.

Why choose log4j2?

Compared with other log systems, log4j2 has less data loss; disruptor technology has more than 10 times better performance than logback in multithreaded environment, and makes use of the concurrency of jdk1.5 to reduce the occurrence of deadlock

The reason for the superior performance of log4j2 is that log4j2 uses LMAX, a lock-free inter-thread communication library instead of the previous queues of logback and log4j. The performance of concurrency has been greatly improved.

Integration steps

Introduction of Jar package

Springboot uses logback's logging framework by default, so you need to exclude logback, otherwise jar dependency conflicts will occur.

Org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-logging org.springframework.boot spring-boot-starter-log4j2

Configuration file

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

Logging: config: xxxx.xml level: cn.jay.repository: trace

The default name is log4j2-spring.xml, saving the configuration in application.yml

Profile template

Log4j is through a .properties file as the main configuration file, but now log4j2 has abandoned this approach, using .xml, .json or .jsn to do it, which may also be an inevitability of technological development, because the readability of properties files is really a little poor.

Brief introduction of configuration parameters

Here is a brief introduction to the commonly used configuration parameters

Log level

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

Trace: tracking, that is, if the program is pushed forward, you can write a trace output.

Debug: debugging, generally as the lowest level, trace is basically not used.

Info: output important information, use more

Warn: warning, some messages are not error messages, but also give programmers some hints.

Error: error message. I use it a lot, too.

Fatal: fatal error.

Output source

CONSOLE (output to console)

FILE (export to file)

Format

SimpleLayout: display in simple form

HTMLLayout: displaying in HTML tabl

PatternLayout: custom form display

PatternLayout Custom Log layout:

% d {yyyy-MM-dd HH:mm:ss, SSS}: log production time, time output to milliseconds%-5level: output log level,-5 means left alignment and fixed output of 5 characters, if not enough to add 0% c: logger name (% logger)% t: output 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: number of lines where the output statement is located, including class name, method name, file name, number of lines hostName: local machine name hostAddress: local ip address

Log4j2 configuration details

Root node Configuration

There are two properties:

Status

Monitorinterval

There are two child nodes:

Appenders

Loggers (indicates that multiple Appender and Logger can be defined).

Status is used to specify the level of print logs for log4j itself.

Monitorinterval is used to specify the monitoring interval for automatic log4j reconfiguration, in s, with a minimum of 5 s.

Appenders node

There are three common seed nodes: Console, RollingFile, File

The Console node is used to define the Appender that is output to the console.

Name: specifies the name of Appender.

Target:SYSTEM_OUT or SYSTEM_ERR, generally only set the default: SYSTEM_OUT.

PatternLayout: output format. Default is:% m% n.

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

Name: specifies the name of Appender.

FileName: specifies the full-path file name of the destination file of the output log.

PatternLayout: output format. Default is:% m% n.

The RollingFile node is used to define and automatically delete the old and create a new Appender beyond the specified condition.

Name: specifies the name of Appender.

FileName: specifies the full-path file name of the destination file of the output log.

PatternLayout: output format. Default is:% m% n.

FilePattern: specifies the rules for transferring and renaming files when Rolling occurs.

Policies: specify the policy for scrolling logs, that is, when to create new log files and output logs.

TimeBasedTriggeringPolicy:Policies child node, time-based scrolling policy. The interval attribute is used to specify how often to scroll. The default is 1 hour. Modulate=true is used to adjust the time: for example, if it's 3 am in the morning, the interval is 4, then the first scroll is in 4am, then 8 am 12 am. Not 7am.

The SizeBasedTriggeringPolicy:Policies child node, based on the scrolling policy that specifies the file size, the size attribute is used to define the size of each log file.

DefaultRolloverStrategy: used to specify that when there are at most several log files in the same folder, delete the oldest and create a new one (through the max attribute).

There are two common Loggers nodes: Root and Logger.

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

Level: log output level, which has 8 levels. It is used to specify the Appender to which the log is output according to the child nodes from low to high: All < Trace < Debug < Info < Warn < Error < AppenderRef:Root.

The Logger node is used to specify the form of the log separately, for example, to specify a different log level for the class under the specified package.

Level: log output level, with a total of 8 levels, from low to high: All < Trace < Debug < Info < Warn < Error < Fatal < OFF.

Name: used to specify the full package path of the class or class to which the Logger applies, inherited from the Root node.

The child node of AppenderRef:Logger, which is used to specify the Appender to which the log is output. If it is not specified, it inherits from Root. If specified, it will be output in the Appender of both the specified Appender and Root. At this point, we can set the additivity= "false" of Logger to output only in the custom Appender.

Easy 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");}}

Simplify the creation of Logger classes using the lombok tool

Lombok is an annotation tool jar package that can help us omit a complicated code. For a specific introduction, you can see my tutorial.

After using lombok, the following code is equivalent to the above code, which makes it easier to use the log.

@ Slf4jpublic class LogExampleOther {public static void main (String... Args) {log.error ("Something else is wrong here");}} that's all for "how to use log4j2 logs in Springboot". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report