当前位置:网站首页>Log4j2
Log4j2
2022-07-02 11:51:00 【xx985】
Log4j2 brief introduction
Apache Log4j 2 It's right Log4j The upgrade , It's better than its predecessor Log4j 1.x Provides significant improvements , And provides Logback Many of the improvements available in , And fixed Logback Some problems in Architecture . Known as the best Java Log framework .
Log4j2 features
Performance improvement
Log4j2 Include based on LMAX Disruptor Library's next generation of asynchronous recorders . In a multithreaded scenario , The throughput of asynchronous recorder is better than Log4j 1.x and Logback high 18 times , Low latency .Auto reload configuration
And Logback equally ,Log4j2 You can automatically reload its configuration when you modify it . And Logback Different , It will not lose log events when reconfiguration occurs .Advanced filtering
And Logback equally ,Log4j2 Support based on Log Context data in events , Mark , Regular expressions and other components for filtering , Besides , Filters can also be associated with recorders . And Logback Different ,Log4j2 You can use generic in any of these situations Filter class .Plug-in architecture
Log4j Use plug-in mode to configure components . therefore , You don't have to write code to create and configure Appender,Layout,Pattern Converter etc. . When configured ,Log4j Automatically identify plug-ins and use them .No garbage mechanism
During steady state logging ,Log4j2 Garbage free in stand-alone applications , stay Web Low garbage in applications . This reduces the pressure on the garbage collector , And it can provide better response performance .At present, the most popular log facade on the market is SLF4J, although Log4j2 It's also a journal facade , Because its log implementation is very powerful , Superior performance . So we usually will Log4j2 Think of it as an implementation of logging
SLF4j + Log4j2 The combination of , It is the most powerful way to realize log function in the market , It is definitely the mainstream trend in the future .
Asynchronous log
Asynchronous logging is log4j2 The biggest feature , The improvement of its performance mainly benefits from asynchronous logging .
Log4j2 There are two ways to implement logging ,One is through AsyncAppender, One is through AsyncLogger
Note that there are two different implementations , It is different in design and source code .AsyncAppender The way
By quoting something else Appender To achieve , When a log event arrives , Another thread will be started to process them . It should be noted that , If in Appender It's abnormal when I'm in the hospital , It is imperceptible to applications . AsyncAppender It should be referenced in Appender After configuration , By default java.util.concurrent.ArrayBlockingQueue Implementation without other external class libraries . When using this Appender When , In a multithreaded environment, you need to pay attention to , Blocking queues are vulnerable to lock contention , This may have an impact on performance . Now , We should consider using lockless asynchronous recorders (AsyncLogger).AsyncLogger The way
AsyncLogger It's just log4j2 The most important function of asynchrony is , It's also The officially recommended asynchronous method .
It makes it possible to call Logger.log Back faster . You have two choices : Global asynchronous and hybrid asynchronous .
Global asynchronous : All logs are recorded asynchronously , You don't have to make any changes to the configuration file , Only need jvm When starting, you can add a parameter to achieve .
Mixed asynchronous : You can use both synchronous logging and asynchronous logging in your application , This makes the configuration of logs more flexible . although Log4j2 Provide a set of exception handling mechanism , Can cover most states , However, there will still be a small number of special cases that cannot be completely handled , For example, if we record the audit log ( One of the special circumstances ), Then the official recommends the use of synchronous logs , For others, it's just a place to record a program log , Using asynchronous logging will greatly improve performance , Reduce the impact on the application itself . The hybrid asynchronous mode needs to be realized by modifying the configuration file , Use AsyncLogger Tag configuration .
<!-- log4j2 rely on **********************************************-->
<!-- slf4j Log facade -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<!-- log4j Adapter -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.12.1</version>
</dependency>
<!-- log4j2 Log facade -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.12.1</version>
</dependency>
<!-- log4j2 Log implementation -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.12.1</version>
</dependency>
<!-- Asynchronous log dependency -->
<dependency>
<groupId>com.lmax</groupId>
<artifactId>disruptor</artifactId>
<version>3.3.7</version>
</dependency><?xml version="1.0" encoding="UTF-8"?>
<Configuration>
<!--
src/main/java/com/log4j2
Configure global properties
-->
<properties>
<property name="logDir">D:</property>
</properties>
<!-- To configure appender -->
<Appenders>
<!-- Configure console output -->
<Console name="consoleAppender" target="SYSTEM_OUT">
<PatternLayout pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} %m%n"/>
</Console>
<!-- Configuration file output -->
<File name="fileAppender" fileName="${logDir}//log4j2.log">
<!-- Configuration file output format -->
<PatternLayout pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} %m%n"/>
</File>
<!--
Split the log file according to the specified rules
fileName: The name of the log file
filePattern: Naming rules of log files after splitting
$${date:yyyy-MM-dd}: According to the date of the day , Create a folder
for example :2021-01-01 In this folder , Record all log information of the day ( The split logs are placed in this folder )
2021-01-02 In this folder , Record all log information of the day ( The split logs are placed in this folder )
rollog-%d{yyyy-MM-dd-HH-mm}-%i.log
Rules for naming files :%i Indicates the serial number , from 0 Start , The purpose is to keep the name of each document from repeating
-->
<!-- <RollingFile name="rollingFile" fileName="${logDir}/rollog.log"-->
<!-- filePattern="${logDir}/$${date:yyyy-MM-dd}/rollog-%d{yyyy-MM-dd-HH-mm}-%i.log">-->
<!-- <!– Log message format –>-->
<!-- <PatternLayout pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} %m%n"/>-->
<!-- <Policies>-->
<!-- <!– At system startup , Trigger split rule , Generate a log file –>-->
<!-- <OnStartupTriggeringPolicy/>-->
<!-- <!– Split according to the size of the file –>-->
<!-- <SizeBasedTriggeringPolicy size="10KB"/>-->
<!-- <!– Split by time node The splitting rule is filePattern–>-->
<!-- <TimeBasedTriggeringPolicy/>-->
<!-- </Policies>-->
<!-- <!– In the same directory , Limit on the number of files , If it exceeds the set value , Then overwrite according to the time , The new rule overrides the old one –>-->
<!-- <DefaultRolloverStrategy max="30"/>-->
<!-- </RollingFile>-->
<!-- Configure asynchronous logging ( Cannot exist asynchronously with the following custom configuration )-->
<!--<Async name="myAsync">
<!– Asynchronous operation of console output –>
<AppenderRef ref="consoleAppender"/>
</Async>-->
</Appenders>
<!-- To configure logger -->
<Loggers>
<!-- Customize logger, Let custom logger For asynchronous logger -->
<!-- includeLocation="false" Indicates that the line number information in the log record is removed , This line number information greatly affects the efficiency of logging ( This line number is not added in production )
In severe cases, the efficiency of logging may be lower than that of synchronous logging
additivity="false" Indicates no inheritance rootlogger -->
<AsyncLogger name="com.log4j2" level="trace"
includeLocation="false" additivity="false">
<!-- Output the console to consoleAppender, Set to asynchronous printing -->
<AppenderRef ref="consoleAppender"/>
<!-- Output the console to fileAppender, Set to asynchronous printing -->
<AppenderRef ref="fileAppender"/>
</AsyncLogger>
<!-- To configure rootlogger -->
<Root level="trace">
<!-- quote Appender -->
<!--<AppenderRef ref="consoleAppender"/>-->
<AppenderRef ref="fileAppender"/>
<!--<AppenderRef ref="rollingFile"/>-->
<!--<AppenderRef ref="myAsync"/>-->
<AppenderRef ref="consoleAppender"/>
</Root>
</Loggers>
</Configuration>package com.log.log4j2;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Log4j2Test {
@Test
public void test01(){
/*--------------------------------------------------------
Introductory cases
Simple use Log4j2 Of The facade + Realization
The default is error Printing of level information
But at present, the most mainstream log uses collocation :slf4j+log4j2
*/
/*--------------------- Use profile -----------------------------------
Use profile
log4j2 It's a reference logback Created , So the configuration file also uses xml
log4j2 It is also the default loading classpath (resources) Under the log4j2.xml Configuration in file
Root tag , All log related information , All are configured in the root tag
<Configuration status="debug" monitorInterval=" The number "></Configuration>
In the root tag , You can add attributes
status="debug" The log output level of the log framework itself
monitorInterval="5" The interval between automatic loading of configuration files , No less than 5 second
*/
/*--------------------------------------------------------
although log4j2 It's also a journal facade , But now the mainstream trend of the market is still slf4j
So we still need to use slf4j As a log facade , collocation log4j2 Powerful log implementation function , Perform log related operations
Next, we configure the most powerful in today's market , The most mainstream log uses collocation :
slf4j+log4j2
1. Import slf4j Log facade
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
2. Import log4j2 Adapter for
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.12.1</version>
</dependency>
3. Import log4j2 Log facade
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.12.1</version>
</dependency>
4. Import log4j2 Log implementation of
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.12.1</version>
</dependency>
Execution principle :slf4j The facade calls log4j2 The facade of , Again by log4j2 Facade call log4j2 The implementation of the
*/
/*--------------- Output the log to a file -----------------------------------------
<File name="fileAppender" fileName="${logDir}//log4j2.log">
<!-- Configuration file output format -->
<PatternLayout pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} %m%n"/>
</File>
*/
/*--------------- Split the log -----------------------------------------
<RollingFile name="rollingFile" fileName="${logDir}/rollog.log"
filePattern="${logDir}/$${date:yyyy-MM-dd}/rollog-%d{yyyy-MM-dd-HH-mm}-%i.log">
<!-- Log message format -->
<PatternLayout pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} %m%n"/>
<Policies>
<!-- At system startup , Trigger split rule , Generate a log file -->
<OnStartupTriggeringPolicy/>
<!-- Split according to the size of the file -->
<SizeBasedTriggeringPolicy size="10KB"/>
<!-- Split by time node The splitting rule is filePattern-->
<TimeBasedTriggeringPolicy/>
</Policies>
<!-- In the same directory , Limit on the number of files , If it exceeds the set value , Then overwrite according to the time , The new rule overrides the old one -->
<DefaultRolloverStrategy max="30"/>
</RollingFile>
*/
// Simple use Log4j2 Of The facade + Realization
// Logger logger = LogManager.getLogger(Log4j2Test.class);
// Use lf4j+log4j2
Logger logger = LoggerFactory.getLogger(Log4j2Test.class);
logger.error("error Information ");
logger.warn("warn Information ");
logger.info("info Information ");
logger.debug("debug Information ");
logger.trace("trace Information ");
}
@Test
public void test02(){
/*
Asynchronous logging implementation ( Allocate threads separately for logging )
The way 1: Use AsyncAppender The way
1. Add asynchronous log dependency
<dependency>
<groupId>com.lmax</groupId>
<artifactId>disruptor</artifactId>
<version>3.3.7</version>
</dependency>
2. stay Appenders In the label , Configure for asynchrony
Use Async label
<!-- Configure asynchronous logging -->
<Async name="myAsync">
// Asynchronous operation of console output
<AppenderRef ref="consoleAppender"/>
</Async>
3.rootlogger quote Async
<Root>
<AppenderRef ref="myAsync"/>
</Root>
*********************************************
Asynchronous logging implementation ( Allocate threads separately for logging )
The way 2: Use AsyncLogger The way
1、 Global asynchronous :
All logs are asynchronous logging , There is no need to make any changes to the configuration file
Just in the classpath resources Let's add one properties Properties file , One step configuration is enough
The file name is required to be :log4j2.component.properties
Log4jContextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector
2、 Mixed asynchronous :(******** Mainly use this *********)
You can use both synchronous and asynchronous logs in your application , This makes the log configuration and output more flexible
demand :
Suppose we now have a custom logger -- com.log
Let custom logger It's asynchronous
Give Way rootlogger It's synchronous
That is to say, the file is in this path (com.log) The log of is an asynchronous operation , Other paths are synchronous
includeLocation="false" Indicates that the line number information in the log record is removed ,
additivity="false" Indicates no inheritance rootlogger
<AsyncLogger name="com.log" level="trace"
includeLocation="false" additivity="false">
<!-- Output the console to consoleAppender, Set to asynchronous printing -->
<AppenderRef ref="consoleAppender"/>
</AsyncLogger>
Be careful :
Before the test , Be sure to comment out the global asynchronous configuration
For the present logger,Log4j2Test01.class
Log4j2Test01 Itself is in our custom logger The next path
Be careful :
If you use asynchronous logging
AsyncAppender、AsyncLogger Don't show up at the same time , There's no need , Effects don't stack
If it appears at the same time , Then the efficiency will be AsyncAppender Mainly
AsyncLogger Global asynchrony and hybrid asynchrony should not occur at the same time , There's no need , Effects don't stack
*/
Logger logger = LoggerFactory.getLogger(Log4j2Test.class);
// A log record
for (int i = 0; i < 2000; i++) {
logger.error("error Information ");
logger.warn("warn Information ");
logger.info("info Information ");
logger.debug("debug Information ");
logger.trace("trace Information ");
}
// System business logic
for (int i = 0; i < 1000; i++) {
System.out.println("------------------");
}
}
}
边栏推荐
- 行业的分析
- Cluster Analysis in R Simplified and Enhanced
- ESP32 Arduino 引入LVGL 碰到的一些问题
- A white hole formed by antineutrons produced by particle accelerators
- Tdsql | difficult employment? Tencent cloud database micro authentication to help you
- Programmer growth Chapter 6: how to choose a company?
- bedtools使用教程
- 通讯录的实现(文件版本)
- [visual studio 2019] create and import cmake project
- Tidb DM alarm DM_ sync_ process_ exists_ with_ Error troubleshooting
猜你喜欢

map集合赋值到数据库

BEAUTIFUL GGPLOT VENN DIAGRAM WITH R

GGPUBR: HOW TO ADD ADJUSTED P-VALUES TO A MULTI-PANEL GGPLOT

mysql链表数据存储查询排序问题

HOW TO ADD P-VALUES TO GGPLOT FACETS

PYQT5+openCV项目实战:微循环仪图片、视频记录和人工对比软件(附源码)

Always report errors when connecting to MySQL database

CTF record

How to Easily Create Barplots with Error Bars in R

HOW TO EASILY CREATE BARPLOTS WITH ERROR BARS IN R
随机推荐
HOW TO EASILY CREATE BARPLOTS WITH ERROR BARS IN R
GGPUBR: HOW TO ADD ADJUSTED P-VALUES TO A MULTI-PANEL GGPLOT
ESP32存储配网信息+LED显示配网状态+按键清除配网信息(附源码)
RPA advanced (II) uipath application practice
MySQL linked list data storage query sorting problem
Some problems encountered in introducing lvgl into esp32 Arduino
Is the stock account given by qiniu business school safe? Can I open an account?
Digital transformation takes the lead to resume production and work, and online and offline full integration rebuilds business logic
excel表格中选中单元格出现十字带阴影的选中效果
【2022 ACTF-wp】
TDSQL|就业难?腾讯云数据库微认证来帮你
Tdsql | difficult employment? Tencent cloud database micro authentication to help you
Tiktok overseas tiktok: finalizing the final data security agreement with Biden government
可昇級合約的原理-DelegateCall
What is the relationship between digital transformation of manufacturing industry and lean production
On April 17, 2022, the five heart matchmaker team received double good news
How to Create a Beautiful Plots in R with Summary Statistics Labels
QT meter custom control
YYGH-BUG-04
CMake交叉编译