In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "what are the advantages of Log4j2". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what are the advantages of Log4j2".
Introduction to Log4j2
Apache Log4j 2 is an updated version of Log4j (1), which is a great improvement over its ancestor Log4j 1. X and a great improvement over logback. In addition to the internal design adjustments, there are mainly the following major upgrades:
Simplified configuration
More powerful parameter formatting
The most exaggerated asynchronous performance
In Log4j 2, it is divided into two modules: * * API (log4j-api) and log4j-core * *. API and slf4j are the same type, belonging to log abstraction / facade, while the implementation part is the core of Log4j 2.
Org.apache.logging.log4j »log4j-api
Org.apache.logging.log4j »log4j-core
The best performance, the strongest asynchronous performance.
This feature can be regarded as the strongest point of Log4j2. Log4j2 in the current JAVA logging framework, asynchronous logging performance is the highest, no one.
First, let's take a look at the benchmark comparison results of several log frameworks (log4j2 official test results):
As can be seen from the figure, the performance of log4j2 in asynchronous (fully asynchronous, non-mixed mode) far exceeds that of log4j1 and logback. The greater the pressure, the greater the gap in throughput. In the 64-thread test, the throughput of log4j2 reaches 180w+/s, while that of logback/log4j1 is less than 20w, a difference of nearly ten times.
Zero GC (Garbage-free)
Since version 2.6 (2016), log4j2 has been running in zero GC mode by default. What is zero GC? That is, GC will not be caused by log4j2.
All kinds of Message objects, string arrays and byte arrays in log4j2 are reused without repeated creation, which greatly reduces the creation of useless objects, thus achieving "zero GC".
Support for higher-performance Imax O writes
Log4j also provides a MemoryMappedFileAppender,I/O part to be implemented using MemoryMappedFile, which can achieve extremely high Imax O performance. But before using MemoryMappedFileAppender, make sure you know enough about MemoryMappedFile, otherwise don't use it easily.
More powerful parameter formatting
Compared with slf4j, API module provides richer parameter formatting functions.
Format parameters using {} placeholders
In slf4j, we can implement the function of "format" in the way of {} (the parameter will directly toString to replace the placeholder), like this:
Logger.debug ("Logging in user {} with birthday {}", user.getName (), user.getBirthdayCalendar ()); the copied code formats the parameters in the form of String.format
Besides the parameter placeholder of {}, log4j2 also supports the form of String.format:
Public static Logger logger = LogManager.getFormatterLogger ("Foo"); logger.debug ("Logging in user% s with birthday% s", user.getName (), user.getBirthdayCalendar ()); logger.debug ("Logging in user% 1$ s with birthday% 2$ tm% 2$ te,%2$ tY", user.getName (), user.getBirthdayCalendar ()); logger.debug ("Integer.MAX_VALUE =%, d", Integer.MAX_VALUE); logger.debug ("Long.MAX_VALUE =%, d", Long.MAX_VALUE); copy code
* * Note that if you want to use the String.format form, you need to use LogManager.getFormatterLogger instead of LogManager.getLogger**
Use logger.printf to format parameters
In the Logger interface of log4j2, there is also a printf method that can be used in the form of String.format without creating a LogManager.getFormatterLogger.
Logger.printf (Level.INFO, "Logging in user% 1$ s with birthday% 2$ tm% 2$ te,%2$ tY", user.getName (), user.getBirthdayCalendar ()); logger.debug ("Opening connection to {}...", someDataSource); copy code "lazy" to log (lazy logging)
Although this function is small, it is very practical.
In some business processes, in order to leave roots or trace back problems, you need to print the input parameters completely. Generally, the input parameters are serialized with JSON/XML and printed at debug level:
Logger.debug ("input message: {}", JSON.toJSONString (policyDTO)); copy code
If you need to retrace a problem, the log level of the system is changed to debug/trace so that you can print. But there is a problem here, although debug does not output content at the info level, the serialized code JSON.toJSONString () must be executed, seriously affecting the efficiency of execution under normal flow.
The expected result is that serialization is not even performed at the info level. Here, you can use isDebugEnable to determine whether the debug level can be output under the current configuration:
If (logger.isDebugEnabled ()) {logger.debug ("input reference message: {}", JSON.toJSONString (policyDTO));} copy the code
This avoids unnecessary serialization, but it's a little hard to write it everywhere, turning one line into three lines.
Log4j2's logger object, which provides a series of lambda support, through which "laziness" logging can be achieved: void debug (String message, Supplier...) ParamSuppliers); void info (String message, Supplier...) ParamSuppliers); void trace (String message, Supplier...) ParamSuppliers); void error (String message, Supplier...) ParamSuppliers); / / equivalent to the following judgment, and then print logger.debug ("input message: {}", ()-> JSON.toJSONString (policyDTO)); if (logger.isDebugEnabled ()) {logger.debug ("input message: {}", JSON.toJSONString (policyDTO));} copy the code
This form of Supplier + Lambda is equivalent to the above judging isDebugEnable and then printing, and three lines of code becomes one line. MMM, it smells good.
Simplified configuration
Log4j 2 supports four forms of XML/JSON/YML/Properties configuration files at the same time, but the most mainstream is XML, which is the most intuitive.
Let's take a look at the configuration file comparison of logback and log4j2, under the configuration of the same function:
Logback.xml logs/app.log logs/archives/app-%d {yyyy-MM-dd} .log.gz 1 GB copy code log4j2.xml Copy the code
In log4j2, the configuration of appender is more concise in syntax from using Appender to implement name-as-a-tag signature:
Copy code adapts to other log abstractions / facades
Since log4j2 is split into two parts, API and implementation, it may also need to adapt to other logging frameworks
Other features
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
Asynchronous queues use high performance queues-* * LMAX Disruptor * *
Appender is rich and supported by JMS/JPA/KAFKA/Http/MONGODB/CouchDB/Socket/Script and other Appender.
Support for custom log levels
……
Basic usage
Finally, after introducing the power of Log4j2, let's introduce the basic use of Log4j2.
Maven dependencies referencing log4j2
Log4j-api already has a dependency in log4j-core, so you can rely on core directly.
Org.apache.logging.log4j log4j-core 2.14.1 copy code
Note that when quoting log4j2, you need to pay attention to whether there are multiple logging frameworks in the project that coexist / conflict and need to be adapted. For details, please refer to the above to adapt to other log abstractions / facades
Profile exampl
The first is the configuration file. The default configuration file path is classpath:log4j2.xml (xml is recommended)
Copy the code XML configuration file syntax; value. Copy the code to create a Logger
Use log4j2's api directly:
Import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; Logger logger = LogManager.getLogger (Log4j2Test.class); logger.error (...); logger.warn (...); logger.info (...); logger.debug (...); logger.trace (...); copy code
If it is used with slf4j, you just need to adapt in advance as mentioned above, and then use slf4j's api. However, if it is a new system, it is recommended to go directly to log4j2's api, you can enjoy all the functions of log4j2, when using api such as slf4j, the above-mentioned functions such as parameter formatting cannot be used.
Full asynchronous configuration (important! )
It is recommended to configure log4j2 full Asynchronous (all async) and add a system variable configuration to your startup script:
-Dlog4j2.contextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector copy Code Thank you for reading, the above is the content of "what are the advantages of Log4j2". After the study of this article, I believe you have a deeper understanding of the advantages of Log4j2, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.