Entry to understanding of log4j2

About log4j2 concept introduction

log4j's official website address

Log frame

Quoting from a discussion about Log4j2 log framework and its use

  • Logging interface (slf4j)
       slf4j (Simple Logging Facade for Java) is a specification, standard, and interface for all logging frameworks. It is not a specific implementation of a framework, because the interface cannot be used independently, and it needs to be combined with Specific log framework implementations are used together (such as log4j, logback), and the province also has a simple implementation
       Jakarta Commons-logging (JCL) is the first log facade interface provided by Apache. Provide simple log implementation and log decoupling function. (The name is now Apache Commons-logging), its implementation default is the log component Jdk14Logger that comes with jdk
  • Log implementation (log4j, logback, log4j2)
    1. log4j is an open source log component implemented by apache
    2. Logback is also designed by the author of log4j. It has better features and is used to replace a log framework of log4j. It is a native implementation of slf4j.
    3. log4j2 is an improved version of log4j 1.x and logback. It is said that some new technologies (lock-free asynchronous, etc.) are adopted. Under multithreading, the throughput of asynchronous log is 18 times that of og4j 1.x, and the performance is higher. Some deadlock bugs are solved, and the configuration is simpler and more flexible. ( 采用自动模块,不仅仅只是实现)

Why do I need a log interface, just use the specific implementation directly?

 The interface is used to customize the specification and can have multiple implementations. When used, it is interface-oriented (the imported packages are all slf4j packages rather than the packages in a specific logging framework), that is, directly interact with the interface instead of directly using the implementation. So for 可以任意的更换实现而不用更改代码中的日志相关代码。
example: the code in the project calls the slf4j interface, the specific implementation is logback, we can replace the code with the implementation of log4j or log4j2 without changing the code

Big change from log4j to log4j2 (important)

The main log framework has been introduced above. log4j is a jar package. The interface and implementation are all together. The interface and implementation of log4j2 are separated. This is the address that log4j2 depends on at runtime . It is similar to the use of slf4j. As shown below

Insert picture description here

  1. The jar package of log4j-api and log4j-core is equivalent to the original jar package of log4j.
  2. In addition to log4j-api and its native implementation log4j-core use no other jar packages, other log frameworks log4j provide bridged jar packages.

The log api determines the calling method of the code in the application (for example, the api is slf4j, then the placeholder assignment method can be used in the code, {}, without paying attention to the underlying implementation)

Log api/framework Bridge jar package (also can be called 适配器) Bridged object description
log4j-api log4j-core Direct implementation, no bridging
log4j-1.2-api log4j-api/log4j-core Overwrite the api in the log4j jar, transfer the call to log4j in the project to log4j2, (need to delete the original log4j jar package)
commons-logging log4j-jcl log4j-api/log4j-core commons-logging uses log4j2 as the implementation
slf4j-api log4j-slf4j-impl log4j-api/log4j-core The bridge package can be understood as log4j2 as an implementation of slf4j
Java Util Logging log4j-jul log4j-api/log4j-core
log4j-api log4j-to-slf4j slf4j-api and its implementation You can use this link to logback (logback-classic/logback-core)

There are other jar packages such as (mainly to provide support):
log4j-web: The Web module supports automatically enabling Log4j in the Servlet container.
log4j-iostreams: Support input to the stream and
omit the following. . . . . . . . .

4. Check the above specific versions from the official website;
5. Introduction to other bridges The integration of slf4j and jul, log4j1, log4j2, logback

Log api/framework Bridge jar package (also can be called 适配器) Bridged object description
slf4j-api slf4j-jdk14 jdk-logging
slf4j-api slf4j-log4j12 log4j
slf4j-api logback-classic/logback-core logback-classic can be regarded as a bridge package
slf4j-api slf4j-jcl commons-logging
jdk-logging jul-to-slf4 slf4j-api 是 java.util.logging
log4j-over-slf4j slf4j-api Log4j is transferred to slf4j, and the original log4j jar is removed
jcl-over-slf4j slf4j-api Remove the commons-logging jar package (

Insert picture description here

  1. Dependency conflict: There is a dependency conflict between this bridged jar package, which cannot be used at the same time, otherwise it will form a closed loop of calls
  • log4j-to-slf4j和log4j-slf4j-impl
  • jul-to-slf4j和slf4j-jdk14
  • log4j-over-slf4j 和slf4j-log4j12
  • jcl-over-slf4j 和 slf4j-jcl

Those versions of log4j support

Reasons for using log4j2 (change introduction)

Official website introduction The
  official website says that log4j needs to be compatible with the very first java version, which becomes difficult to maintain, so there is log4j2, and some reasons for using log4j instead of slfj/logback are listed:

  1. Both Log4j 1.x and Logback will lose events during reconfiguration. Log4j 2 will not.
  2. In a multithreaded scenario, the throughput of the asynchronous logger is 10 times higher than Log4j 1.x and Logback, and the latency is an order of magnitude lower.
  3. Log4j 2 is garbage-free for stand-alone applications and low garbage for web applications during steady-state logging. This reduces the pressure on the garbage collector and can provide better response time performance.
  4. Log4j 2 uses a plug-in system. By adding new add-ons, filters, layouts, search and pattern converters, without any changes to Log4j, it becomes very easy to extend the framework.
  5. Because the plug-in system configuration is simpler. The entries in the configuration do not need to specify the class name.
  6. Support custom log level. The custom log level can be defined in code or configuration.
  7. Support lambda expressions. Only when the requested log level is enabled, client code running on Java 8 can use lambda expressions to construct log messages lazily. No explicit level checking is required, resulting in cleaner code.
  8. Support message objects. Messages allow support for interesting and complex structures to be passed through the logging system and be manipulated efficiently. Users can freely create their own message types, and write custom layouts, filters, and lookups to manipulate them.
  9. Log4j 1.x supports Filters in the appendix. Logback adds TurboFilters, allowing events to be filtered before they are processed by the logger. Log4j 2 supports filters that can be configured to process events before they are processed by the logger, as if they were processed by the logger or appender.
  10. Many log appenders do not accept Appenders and only send data in a fixed format. Most Log4j 2 appendices accept Appenders, allowing data to be transmitted in any desired format
  11. The layout (Appenders) in Log4j 1.x and Logback returns a string. This led to the problems discussed in the Logback encoder. Log4j 2 uses a simpler method, that is, the layout always returns a byte array. This has the advantage that they can be used in practically any additional program, not just additional programs that write to the output stream.
  12. Syslog Appender supports TCP and UDP, and also supports BSD syslog and RFC 5424 formats
  13. Log4j 2 takes advantage of Java 5 concurrency support and performs locking at the lowest level possible. Log4j 1.x is already aware of the deadlock problem. Many of these are fixed in Logback, but many Logback classes still require a fairly high level of synchronization.
  14. This is an Apache Software Foundation project that follows the community and support model used by all ASF projects. If you want to contribute or get the right to submit changes, just follow the path outlined in the contribution.

The structure system of log4j

Official website addressThe introduction address

Class diagram of log4j main classes

Insert picture description here
Combined with this picture, it should be easier to understand the log4j configuration file

Inheritance rules of log4j2 logger

This is not much different
from log4j . To understand, refer to the following log4j from entry to understanding. The
following is a code example for obtaining the root logger (obtained by name, it can also be used to retrieve other loggers)

Logger logger = LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);
//或
Logger logger = LogManager.getRootLogger();

Related introduction of the class

LoggerContext

The recorder context serves as the anchor point of the record system. However, depending on the situation, there may be multiple active logger contexts in the application. (The application and other applications share the same environment)

Configuration

Each logger context has an active configuration. This configuration contains all appenders, context-scoped filters, recorder configurations, and contains a reference to StrSubstitutor. During the reconfiguration, there will be two configuration objects.一旦所有记录器被重定向到新配置,旧配置将被停止并丢弃。

Logger

The logger is created by calling LogManager.getLogger. The recorder itself does not perform direct operations. It just has a name and is associated with a logger configuration. It extends the abstract recorder and implements the required methods. When modifying the configuration, the logger may be associated with a different logger configuration, resulting in its behavior being modified

Retrieving Loggers

The LogManager.getLoggersame logger object is obtained by the method with the same name

LoggerConfig

The recorder configuration object is created when the recorder is declared in the record configuration. The logger configuration contains a set of filters that must allow the LogEvent to pass before passing it to any appenders. It contains a reference to a set of additional programs that should be used to handle the event.

Log Levels

 The level used to identify the severity of the event. The level is organized from the most specific to the least: TRACE, DEBUG, INFO, WARN, ERROR, and FATAL. The level api address is provided here

1. Every Logger 可以有其单独的LoggerConfig,LoggerConfig也可以继承父记录器, the following is a chart example of Logger's inheritance relationship

The following example X\XY can be regarded as the class name (also the name of the recorder).
Example 1

Logger Name Assigned LoggerConfig LoggerConfig Level Logger Level
root root DEBUG DEBUG
X root DEBUG DEBUG
XY root DEBUG DEBUG
X.Y.Z root DEBUG DEBUG

Example 2

Logger Name Assigned LoggerConfig LoggerConfig Level Logger Level
root root DEBUG DEBUG
X X ERROR ERROR
XY XY INFO INFO
X.Y.Z X.Y.Z WARN WARN

Example 3

Logger Name Assigned LoggerConfig LoggerConfig Level Logger Level
root root DEBUG DEBUG
X X ERROR ERROR
XY X ERROR ERROR
X.Y.Z X.Y.Z WARN WARN

Example 4

Logger Name Assigned LoggerConfig LoggerConfig Level Logger Level
root root DEBUG DEBUG
X X ERROR ERROR
XY X ERROR ERROR
X.Y.Z X ERROR ERROR

Example 5

Logger Name Assigned LoggerConfig LoggerConfig Level Logger Level
root root DEBUG DEBUG
X X ERROR ERROR
XY XY INFO INFO
X.YZ X ERROR ERROR

Example 6 The description here is that the recorder inherits the configuration of its parent class, if not, it goes back up to the root

Logger Name Assigned LoggerConfig LoggerConfig Level Logger Level
root root DEBUG DEBUG
X X ERROR ERROR
XY X ERROR
X.Y.Z X ERROR
  1. The following table describes the filtering level configured by LoggerConfig and the level of log events that it allows to pass
    Insert picture description here

Filter

  1. Automatic level log filtering, mentioned in level
  2. Log4j provides filters, which can be used before control is passed to any logger configuration, after control is passed to the logger configuration but before any appender is called, after control is passed to the logger configuration but before a specific appender is called, and Apply on each add-on.
  3. 过滤器(Filter)可以返回三个结果之一:“接受(Accept)”、“拒绝(Deny )”或“中立(Neutral)”
    a. The accepted response means that no other filters should be called and the event should continue.
    b. A rejected response means that the event should be ignored immediately and control should be returned to the caller.
    c. Neutral's response indicates that the event should be passed to other filters. If there are no other filters, the event will be processed.
  4. Although the filter can accept an event, the event may not be logged. This may happen when an event is accepted by the pre-logger configuration filter, but then rejected by the logger configuration filter or rejected by all appenders.

Appender

. Log4j allows logging requests to be printed to multiple destinations. In log4j, the output destination is called Appender. At present, onsole, files, remote socket servers, Apache Flume, JMS, remote UNIX Syslog daemons, and various database APIswe have a corresponding the Appender, a record may be connected by a plurality of additional code addLoggerAppenderaddition method.
Insert picture description here#### Appender rules
The rules of this appender are the same as log4j . Log4j inherits the rules of appender from entry to understanding

LayOut

Layout is responsible for formatting LogEvent according to the user's wishes, associated with Appender, and defining the output format,

StrSubstitutor and StrLookup

Migration of log4j1.X

Front:

  1. No access to methods and classes inside the Log4j 1.x implementation, such as Appenders, logger repository, or category callAppenders method.
  2. And you must not configure it in the form of code (cool)
  3. It cannot be configured by calling the class DOMConfigurator or the attribute Configurator.

operating:

  1. Remove the dependency of log4j1.x and replace it with log4j-1.2-api (it should overwrite the api part of log4j so that it can call the api of log4j2).
  2. Add log4j-api and its implementation log4j-core
  3. Replace configuration file()
  4. Pay attention to the exclusion of dependencies, you need to change the log configuration file location classPath specified in springBoot,

Detailed operation connection:

  1. Official website address of log4j migration
  2. Official website translation of log4j migration
  3. Log4j is smoothly upgraded to log4j2 (big cow)
  4. log4j upgrade log4j2

log4j2 uses placeholder output form

I can’t write anymore, let’s talk about it later

Guess you like

Origin blog.csdn.net/qq_40182873/article/details/87777709