Log4j seems to be obsolete. Why write this article?

Log4j, log4j2, logback from basic ideas on the realization of the three is consistent, is output to a file, and see the configuration files are the same (logger, appenders, layout), but both have more advanced features than the former, after this block can be singled out. So if you want to get to the bottom of it, it’s a good place to start.

Simple experience

<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>
Copy the code

The test class:

public static void main(String[] args) {
    Logger logger = Logger.getLogger(Log4jTest.class);
    logger.debug("log4j debug");
    logger.info("log4j info");
    logger.error("log4j error");
}
Copy the code

Output to the console: log4j.properties

# define a log adapter called csAppender log4j. Appender. CsAppender = org.. Apache log4j. ConsoleAppender log4j.appender.csAppender.Threshold=INFO log4j.appender.csAppender.Target=System.out log4j.appender.csAppender.layout=org.apache.log4j.PatternLayout log4j.appender.csAppender.layout.ConversionPattern=[%d] [% T] [% C. %M:%L] [%-5p]: %M % N # Set the root log level to DEBUG and set the output to the csAppender log4j.rootLogger= DEBUG,csAppenderCopy the code

Output to the file: log4j.properties

# define a log adapter called fileAppender log4j. Appender. FileAppender = org.. Apache log4j. DailyRollingFileAppender log4j.appender.fileAppender.Threshold=INFO log4j.appender.fileAppender.File=D://data//usr//local//logs//home//log4j-log.log log4j.appender.fileAppender.DatePattern  = '.'yyyy-MM-dd'.log' log4j.appender.fileAppender.Encoding=UTF-8 log4j.appender.fileAppender.Append=true log4j.appender.fileAppender.layout=org.apache.log4j.PatternLayout log4j.appender.fileAppender.layout.ConversionPattern=[%d] [%t] [%-5p] [%c.%M:%L]: Set the root log level to DEBUG and set the output to the fileAppender log4j.rootLogger= DEBUG,fileAppenderCopy the code

The root logging instance in the example configuration above uses csAppender (console) and fileAppender (file) appenders to output log content to the destination, respectively. Of course, you can also output at the same time. Log4j website is not configured for instructions, but in the org.. Apache log4j. PropertyConfigurator# doConfigure method can see the full information on the annotation.

The first step is to configure the root Logger format as follows:

Log4j. rootLogger = [level], appenderName1, appenderName2,...Copy the code
  • Level Indicates the lowest log level. The value can be OFF, FATAL, ERROR, WARN, INFO, DEBUG, ALL, or a custom level. For example, if the INFO level is set, ALL DEBUG logs in applications will not be printed.

  • appenderName

    Specify where log information is to be output. Multiple output destinations can be specified simultaneously, separated by commas. Example: log4j.rootLogger = INFO,A1,B2,C3

Step 2 Configure the format of the log output destination (appender) :

# For appender named log4j.appender.appenderName=fully.qualified.name.of.appender.class # Set appender specific options.  log4j.appender.appenderName.option1=value1 ... log4j.appender.appenderName.optionN=valueNCopy the code

The three major components

Log4j has three main components: loggers, appenders and layouts. These three types of components work together to enable developers to log messages according to message type and level, and to control at runtime how these messages are formatted and where they are reported.

Log4j has three main components: Loggers, Appenders, and Layouts. This can be simply understood as log types, where logs are to be output, and in what form logs are to be output. Using these three components together makes it easy to record the type and level of information and to control the style and location of log output at run time.

Logger

Loggers components in this system are divided into five levels: DEBUG, INFO, WARN, ERROR, and FATAL. The five levels are in sequence. DEBUG < INFO < WARN < ERROR < FATAL specifies the importance of a log message. Log4j has a rule that only logs of a specified level or higher are output. If the Loggers level is set to INFO, logs of the INFO, WARN, ERROR, and FATAL levels are displayed. Logs of the DEBUG level lower than INFO are not displayed.

Define the logger

Log4J always has a rootLogger, even if no configuration is displayed, and the default output level is DEBUG. All other loggers inherit from the rootLogger (if the other loggers have not defined their output level separately).

Second, the level of Log4J (Hierarchy) is to use ‘. ‘to separate, such as log4j.logger.com.example.test, is not to say that the Log4J. Behind the logger must be a specific package name and the name of the class, the name can be custom, We can even define A log4j.logger.a.b.c, as shown in the following example, which creates three logger instances, A, A.B, and A.B.C

Log4j.properties log4j.logger.a.b.c = ERROR,appenderName ## Obtain the log object named A.B in the code logger logger = Logger.getLogger("A.B")Copy the code

When no logger is available, the search action is passed until the root node still does not find the logger with the corresponding name, and the root Logger instance is returned.

Appender

Each enabled logging request for a given logger will be forwarded to all the appenders in that logger as well as the appenders higher in the hierarchy

Logger objects can be inherited and appenders can be appended. When a lower-level Logger object is called to log, log4j prints the request to all appenders currently attached to the logger.

Assume that the following configuration files exist:

log4j.rootLogger=DEBUG,consoleAppender log4j.logger.com=DEBUG,consoleAppender log4j.logger.com.A.B=INFO,consoleAppender log4j.logger.com.X=INFO,consoleAppender ## ... Omit the consoleAppender configurationCopy the code

The log4J log container has the following instance relationship:

Logger named A.B outputs logs to the console three times because A.B inherits all of A’s and A’s parent logger’s appenders. This inheritance only adds the parent logger’s appender to its appender list. The parent logger’s output level does not affect the child logger’s output.

log4j.rootLogger=DEBUG,consoleAppender
log4j.logger.A=DEBUG,consoleAppender
log4j.logger.A.B=INFO,consoleAppender
log4j.additivity.A.B=false
Copy the code

A logger log named A.B is only exported to its own appender and does not inherit any parent logger’s appender.

If you want to limit the level of log output to appenders, you need to use threshold.

log4j.threshold=ERROR
Copy the code

To control all appenders, i.e., logs that are output to all appenders, regardless of their original level, cannot be lower than the level specified by threshold.

log4j.appender.Console.threshold=ERROR 
Copy the code

Used to control the output level of the specified appender.

The Log4j logging system also provides many powerful features, such as the ability to export logs to different locations such as Console, Files, create new Files based on the number of days or the size of the file, and send them as streams to other locations.

The console (the console)

log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.ImmediateFlush=true
log4j.appender.console.Target=System.err
log4j.appender.console.layout=org.apache.log4j.PatternLayout
Copy the code

LogFile (logFile)

log4j.appender.logFile=org.apache.log4j.FileAppender
log4j.appender.logFile.Threshold=DEBUG
log4j.appender.logFile.ImmediateFlush=true
log4j.appender.logFile.Append=true
log4j.appender.logFile.File=D:/logs/log.log4j
log4j.appender.logFile.layout=org.apache.log4j.PatternLayout
Copy the code

Roll back a file

  • Threshold=WARN: Specifies the lowest level of log output. The default level is DEBUG
  • ImmediateFlush=true: Indicates that all messages will be output immediately. If the value is set to false, none will be output. The default value is true.
  • Append=false: true adds the message to the specified file. False overwrites the message to the specified file. The default value is true.
  • File=D:/logs/logging.log4j: Specifies the message to be output to the logging.log4j File.
  • MaxFileSize=100KB: the suffix can be KB, MB, or GB. When the log file reaches this size, it will automatically scroll, moving the original contents to the logging.log4j.1 file.
  • MaxBackupIndex=2: Specifies the maximum number of scrolling files that can be generated. For example, 2 produces two scrolling files, logging.log4j.1, logging.log4j.2, and one logging.log4j file.
log4j.appender.rollingFile=org.apache.log4j.RollingFileAppender
log4j.appender.rollingFile.Threshold=DEBUG
log4j.appender.rollingFile.ImmediateFlush=true
log4j.appender.rollingFile.Append=true
log4j.appender.rollingFile.File=D:/logs/log.log4j
log4j.appender.rollingFile.MaxFileSize=200KB
log4j.appender.rollingFile.MaxBackupIndex=50
log4j.appender.rollingFile.layout=org.apache.log4j.PatternLayout
Copy the code

Periodically roll back log files (dailyfiles)

DatePattern=’.’ YYYY-mm: generates a new log file every month. The log file name for the current month is logging.log4j and the log file name for the previous month is logging.log4j.YYYY-mm. Alternatively, you can specify the following format for scrolling log files by week, day, hour, or rank:

- YYYY-MM: monthly - YYYY-WW: weekly - YYYY-MM-DD: daily - YYYY-MM-DD-a: twice a day - YYYY-MM-DD-hh: hourly - YYYY-MM-DD-hh-mm: every minuteCopy the code
log4j.appender.dailyFile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.dailyFile.Threshold=DEBUG
log4j.appender.dailyFile.ImmediateFlush=true
log4j.appender.dailyFile.Append=true
log4j.appender.dailyFile.File=D:/logs/log.log4j
log4j.appender.dailyFile.DatePattern='.'yyyy-MM-dd
log4j.appender.dailyFile.layout=org.apache.log4j.PatternLayout
Copy the code

Applied to the socket

log4j.appender.socket=org.apache.log4j.RollingFileAppender
log4j.appender.socket.RemoteHost=localhost
log4j.appender.socket.Port=5001
log4j.appender.socket.LocationInfo=true
Copy the code

Sends logs to the specified mail

log4j.appender.mail=org.apache.log4j.net.SMTPAppender
log4j.appender.mail.Threshold=FATAL
log4j.appender.mail.BufferSize=10
log4j.appender.mail.From = [email protected]
log4j.appender.mail.SMTPHost=mail.com
log4j.appender.mail.Subject=Log4J Message
log4j.appender.mail.To= [email protected]
log4j.appender.mail.layout=org.apache.log4j.PatternLayout
Copy the code

Applied to a database

log4j.appender.database=org.apache.log4j.jdbc.JDBCAppender log4j.appender.database.URL=jdbc:mysql://localhost:3306/test log4j.appender.database.driver=com.mysql.jdbc.Driver log4j.appender.database.user=root log4j.appender.database.password=  log4j.appender.database.sql=INSERT INTO LOG4J (Message) VALUES('=[%-5p] %d(%r) --> [%t] %l: %m %x %n') log4j.appender.database.layout=org.apache.log4j.PatternLayoutCopy the code

Layout

Sometimes users want to format their own log output to their preferences, and Log4j can attach Layouts to Appenders to do so. Layouts offer four types of log output styles, including HTML style, free-style, log level and information style, and log time, thread, and category styles. Commonly used classes are as follows:

- org. Apache. Log4j. HTMLLayout (layout) in HTML form - org.. Apache log4j. PatternLayout (the flexibility to specify layout mode) Org, apache log4j. SimpleLayout (string) contains the log information level and information - org.. Apache log4j. TTCCLayout (such as time, threads, category contains the log information)Copy the code

Formatting symbol Description

%p: indicates the priority of the output log information, including DEBUG, INFO, WARN, ERROR, and FATAL. The default format is ISO8601. You can also specify a format after it, for example, % D {YYYY /MM/ DD HH: MM :ss,SSS}. %r: Indicates the number of milliseconds elapsed between the start of the application and the output of this log message. %t: outputs the name of the thread that generated the log event. %L: the location of the output log event. It is equivalent to % C. %M(%F:%L), including the full name of the class, method, file name, and the number of lines in the code. For example, test.testlog4j. main(testlog4j.java :10). %c: Indicates the class to which the output log information belongs, usually the full name of the class. %M: indicates the name of the method that generates logs. %F: indicates the name of the file where the output log message is generated. %L: : Line number in output code. %m: : Prints the specific log information specified in the code. %n: Outputs a carriage return newline character, "RN" on Windows or "n" on Unix. %x: Outputs the NDC(nested diagnostic environment) associated with the current thread, especially in multi-client, multi-threaded applications such as Java Servlets. %% : Outputs a "%" character. In addition, you can place modifiers between % and format characters to control the minimum length, maximum length, and alignment of text. C: Specifies the name of the output category. The minimum length is 20. If the category name length is less than 20, right-align by default. 2)% -20C: "-" indicates left alignment. 3)%.30c: Specifies the name of the output category. The maximum length of the category name is 30. If the category name is larger than 30, the extra characters will be cut off, but if the category name is smaller than 30, no Spaces will be added.Copy the code

Practical analysis

Define two appenders output to the console and file, respectively for called com. Fingard. Rh. The RHF. The ryb. Manager. UnifiedServiceManager log into the output level of the ERROR, and disable the appender inheritance, Outputs only in the appender of the current logger. In the UnifiedServiceManager class, if the following method is used to obtain logger, logs are output only at the ERROR level or higher

Logger logger1 = Logger.getLogger(UnifiedServiceManager.class)
Copy the code

Logger getLogger(Class Clazz) is passed in as loggerName by default. So get logger1 is specified in the configuration file called com. Fingard. Rh. The RHF. The ryb. Manager. UnifiedServiceManager log objects.

Use skills

Define variables in the.properties configuration file

LOG_HOME=D://data//usr//local//logs//home1

log4j.rootLogger=debug,fileAppender
# ...
log4j.appender.fileAppender.File=${LOG_HOME}//log4j-log.log
Copy the code

Almost a hidden feature…

Different log4j modules output to different files

Different modules: Define multiple Logger instances with package name loggerName

Different files: Define multiple Fileappenders and associate them with logger instances corresponding to loggerName

Reference: www.cnblogs.com/0201zcr/p/5…

The log output path changes dynamically

Reference: blog.csdn.net/wiwipetter/…

reference

  • Logging.apache.org/log4j/1.2/m…
  • org.apache.log4j.PropertyConfigurator#doConfigure