Eighty-six, Log4j and Log4j2 Do you really understand?

A complete software, the log is essential. Programs need to output a lot of information to the console or files from the development, testing, maintenance, operation and other links. The output of this information, in many cases, cannot be done using System.out.println().

The log information is divided into debug log, operation log, exception log , etc. according to the purpose and record content. There are many technologies for logging, such as logger technology of jdk , log4j and log4j2 technology of apache , etc.

The full name of Log4j is Log for java, that is, a logging tool dedicated to the java language. It currently has two versions: Log4j and Log4j2.

content

Download of Log4j

log level

log output control file

Log implementation steps in the program

Log output control file analysis

Define the log appender appender

decorated log appender

Configure root logger

Log implementation steps


Download of Log4j

Log4j download address: http://logging.apache.org/

log level

In order to facilitate the output and display of log information, the log content is managed hierarchically. The log level is divided into 6 levels from high to low: fatal ( fatal ) , error , warn , info , debug , trace ( stack ) .

Why should logs be graded?

Whether the log is output to the console or a file, its output will reduce the running efficiency of the program. However, due to the needs of debugging, operation and maintenance, and customer requirements, necessary log output is required . At this time, you must add a log output statement to the code.

If these output statements are all executed when the program is running, it will inevitably reduce the running efficiency. For example, using System.out.println() to output information to the console, all the output statements will be executed. It will greatly reduce the execution efficiency of the program. And to make it not output, the only way is to delete all these output statements one by one. This is a time-consuming and laborious process.

The hierarchical management of log information makes it easy to control the output content and output location of the information: which information needs to be output and which information does not need to be output, only needs to be slightly modified in a log output control file. The output statement in the code does not need any modification.

From this point of view, the log writing in the code is actually writing a large number of output statements. However, these output statements are special, they have levels and are not necessarily executed during program execution. Their execution is controlled by another control file.

log output control file

The log output control file of Log4j is mainly composed of three parts:


  1. Output location of log information: Control the location where the log information will be output, whether it is a console or a file, etc.
  2. Output format of log information: Controls the display format of log information, that is, in what string format is it displayed.
  3. Output level of log information: Control the display content of log information, that is, which levels of log information are displayed.

With the log output control file, as long as the content and level of the log information are set in the code, the output of these log information can be controlled through the control file.

Log implementation steps in the program

Project: log4j

To write log statements in your own program, you can follow these steps:

(1) Import the Jar package

        Import the jar package required by log4j in the project. Unzip the zip file of the Log4j framework, and there is its Jar package in its root directory.

(2) Put in the log output control file

        Place the properties file log4j.properties directly under the src of the project.

(3) Implement logging in the code

        Create the log object Logger in the class to output the log, and add the log output statement in the code through the Logger method. To log output in Java code, you need to use the static method getLogger() of the Logger class.

        Note that Logger is a class in the org.apache.log4j package.

 In the future, these log output statements will be output according to the log level settings in the log4j.properties file, and will be output to the specified location. The output result is: output the information of the specified level and its higher level. If info level is specified, information of fatal, error, warn, info level will be output. For this example, the following three sentences are executed, but the debug() method is not executed.

Log output control file analysis

The log properties file log4j.properties is dedicated to controlling log output. It mainly controls three aspects:

  • Output location: Control the location where the log will be output, whether it is the console or a file, etc.
  • Output layout: Controls the display form of log information.
  • Output level: Controls the log level to output.

The log properties file consists of two objects: the log appender and the root log.

        The root log, which is the logger in Java code, is mainly composed of two attributes: log output level and log appender.

        The log appender is defined by the log output location and modified by many other properties, such as output layout, file location, file size, etc.

Define the log appender appender

The so-called log appender is to append a lot of other setting information to the log recorder. The essence of the appender is an interface, and its definition syntax is: log4j.appender.appenderName = output location

appenderName is a custom name.

        The output location is the type specified by log4j, which is the implementation class of some defined appender interfaces. View the JavaDoc in the index.jsp of the site directory site in the decompression directory of the log4j framework , and you can see the API of log4j.

For example, a console appender named console is defined:

 Commonly used adder implementation classes are as follows:

  • org.apache.log4j.ConsoleAppender : log output to console
  • org.apache.log4j.FileAppender : log output to file
  • org.apache.log4j.RollingFileAppender : A new log file will be generated when the log file size reaches the specified size
  • org.apache.log4j.DailyRollingFileAppender : Generates a log file every day

decorated log appender

The so-called decorated log appender is to add some properties to the defined appender to control the output to the specified location.

Different appenders have different decoration properties.

(1) Console appender:

Target : Controls the usage target output to the console . Its value is System.out or Sytem.err.

The difference is that System.out is displayed to the console in black font, while System.err is displayed in red font.

(2) File appender:

 File : The file location and file name of the log output.

(3) Rolling file appender:

MaxFileSize : Used to specify the maximum size of the log file. If the file exceeds the specified value, another log file will be automatically generated.

Log4j common layout types:

  • org.apache.log4j.HTMLLayout: Web page layout, in HTML table layout.
  • org.apache.log4j.SimpleLayout: Simple layout containing the level of log information and an information string.
  • org.apache.log4j.PatternLayout: matcher layout, which can flexibly specify layout patterns. It mainly controls the specific output format by setting the value of the ConversionPattern attribute of PatternLayout.

There are many control characters in the value of ConversionPattern, and the meanings of these characters are shown in the following table:

parameter illustrate example
%c List the full name of the logger namespace, if you add {<level>}, it means to list the namespace of the specified level from the innermost level

log4j configuration file

Parameter example
output display medium
Assume the logger namespace is "abc"
%c a.b.c
%c{2} b.c
%20c If the length is less than 20, the left is filled with spaces
%d Display logging time, {<date format>} uses the date format defined by IS08601

%d{yyyy/MM/dd

HH:mm:ss,SSS}

2022/3/27 9:40:30,117
%F Display the name of the source file that called the logger %F MyClass.java
%L Show the line of code that calls the Logger %L 129
%m show output message %m This is a message for debug
%M Displays the name of the method calling the logger %M main
%n newline under the current platform %n

Represents rn under Windows

In UNIX it means n

%p Display the priority of this log %p INFO
%t output the name of the thread that generated the log event %t MyClass

Configure root logger

Configure rootLogger so that code loading controls the output of the log. Its syntax is:

log4j.rootLogger = [ level ] , appenderName, …

Among them, level is the priority of logging, which is divided into OFF, FATAL, ERROR, WARN, INFO, DEBUG, ALL. Log4j recommends using only four levels, the priority from high to low is ERROR, WARN, INFO, DEBUG.

OFF is to turn off the log function.

Low-level ones can display high-level ones, but high-level ones cannot display low-level ones. So, the higher the level, the less information will be displayed in the future.

og4j2 is an upgrade to Log4j, which has undergone major changes in configuration and use.

Log implementation steps

Project: log4j2

(1) Import the Jar package

To use Log4j2, you need to import its Jar package. The following two jar packages are found in the decompression directory of the Log4j framework:

 (2) Put in the log output control file

        Put the file log4j2.xml directly under the src of the project. log4j2 configuration files are XML files and properties files are no longer supported. The default file name is log4j2.xml. It is stored in the classpath.

(3) Implement logging in the code

        Create the log object Logger in the class to output the log, and add the log output statement in the code through the Logger method. The log object is obtained through the getLogger() method of the static class LogManager.

        Note that both Logger and LogManager are classes in the org.apache.logging.log4j package, not in the org.apache.log4j package.

        log4j2 configuration files are XML files and properties files are no longer supported. The default file name is log4j2.xml. It is stored in the classpath.

If log4j2.xml is not set, the system will use the default log configuration: only error level information will be output to the console.

 Configuration file description:

(1) <configuration/> tag

        The status attribute of the <configuration/> tag is used to set the log display level of Log4j2 itself, which is generally OFF and not displayed. Of course, it can also be set to ERROR, DEBUG and other levels.

(2) <Console/> tag

        The target attribute of the <Console/> tag is used to set the target form of the output, and its value is generally: SYSTEM_OUT or SYSTEM_ERR

(3) <File/> tag

        The fileName attribute of the <File/> tag is used to set the file saving path and file name of the file. As this example means, the log file name is test.log, and it is stored in the log subdirectory under the root directory of the current project.

The append attribute is used to set whether to append the log to the specified file.

        The <SizeBasedTriggeringPolicy/> sub-tag of the <RollingFile/> tag is used to specify the maximum file size of each log file. When the specified value is reached, a new log file will be created automatically.

(4) <Rollingfile/> tag

        fileName specifies the storage directory and the name of the first log file. filePattern Specifies the filename of the newly created log file. This example also compresses the file.

 (5) <loggers/> tag

        Used to configure the root Logger object to specify the logger to use, and the level to display.

        Its subtag <root/> is used to specify the logger to use. The attribute level of this subtag is used to specify the display level. The logger refers to the logger defined in <appenders/> through the subtag <appender-ref/> of <root/>.

It should be noted that as long as <File/>, <RollingFile/>, etc. are defined in <appenders/>, and the directory where the logs are stored is specified, these directories will be created automatically. They are used regardless of whether they are declared in the <root/> of <loggers/>.


Guess you like

Origin blog.csdn.net/m0_54925305/article/details/123768005