Log4j configuration details

Posted by akufen on Mon, 24 Jan 2022 15:47:11 +0100

Log4j.properties configuration details

1, Log4j introduction

Log4j has three main components:

  • Loggers: log category and level;
  • Appenders: the place where the log is to be output;
  • Layouts: how are logs output

1.1 Loggers

Loggers components are divided into five levels in this system: DEBUG, INFO, WARN, ERROR and FATAL. These five levels are in order. DEBUG < INFO < WARN < ERROR < FATAL are used to specify the importance of this log information respectively. It is important to understand this,
Log4j has a rule: only log information with a level not lower than the set level is output. Assuming that Loggers level is set to INFO, log information of INFO, WARN, ERROR and fat levels will be output, while DEBUG with a level lower than INFO will not be output.

1.2 Appenders

Disabling and using log requests is only the basic function of Log4j. The Log4j log system also provides many powerful functions, such as allowing logs to be output to different places, such as Console and Files. New Files can be generated according to days or file size, and can be sent to other places in the form of streams.
The commonly used classes are as follows:

  • org.apache.log4j.ConsoleAppender
  • org.apache.log4j.FileAppender (file)
  • org. apache. log4j. Daily rollingfileappender (one log file is generated every day)
  • org.apache.log4j.RollingFileAppender (a new file is generated when the file size reaches the specified size)
  • org.apache.log4j.WriterAppender (send log information in stream format to any specified place)

Configuration mode:

log4j.appender.appenderName = className
log4j.appender.appenderName.Option1 = value1
...
log4j.appender.appenderName.OptionN = valueN

1.3 Layouts

Log4j can complete this function by attaching Layouts after Appenders.
Layouts provides four log output styles, such as HTML style, freely specified style, style containing log level and information, and style containing log time, thread, category and other information.
The commonly used classes are as follows:

  • org.apache.log4j.HTMLLayout (layout in HTML table form)
  • org.apache.log4j.PatternLayout (layout mode can be specified flexibly)
  • org.apache.log4j.SimpleLayout (contains the level and information string of log information)
  • org.apache.log4j.TTCCLayout (including log generation time, thread, category and other information)

Configuration mode:

log4j.appender.appenderName.layout =className
log4j.appender.appenderName.layout.Option1 = value1
...
log4j.appender.appenderName.layout.OptionN = valueN

2, Configuration details

In practical application, to make Log4j run in the system, the configuration file must be set in advance. The configuration file actually sets the Logger, Appender and Layout accordingly.
Log4j supports two configuration file formats:

  • One is a file in XML format,
  • One is the properties property file.

Next, take the properties property file as an example to introduce log4j Properties.

2.1 configuring the root Logger

log4j.rootLogger = [ level ] , appenderName1, appenderName2, ...
log4j.additivity.org.apache=false: express Logger Not in the parent Logger of appender Output in, default to true. 

**1. level: * * set the lowest level of logging. The values that can be set include OFF, fat, ERROR, WARN, INFO, DEBUG, ALL or user-defined levels. Log4j recommends using only the middle four levels. By setting the level here, you can control the switch of log information at the corresponding level in the application. For example, if the INFO level is set here, ALL DEBUG level log information in the application will not be printed.
**2. appenderName: * * specifies where to output log information. Multiple output destinations can be specified at the same time, separated by commas.
For example: log4j rootLogger=INFO,A1,B2,C3

2.2 configure log information output destination (appender):

log4j.appender.appenderName = className

**appenderName: * * Custom appenderName, in log4j Used in rootlogger settings;
className: the settable values are as follows:

  • (1)org.apache.log4j.ConsoleAppender
  • (2)org.apache.log4j.FileAppender (file)
  • (3)org. apache. log4j. Daily rollingfileappender (one log file is generated every day)
  • (4)org.apache.log4j.RollingFileAppender (a new file is generated when the file size reaches the specified size)
  • (5)org.apache.log4j.WriterAppender (send log information in stream format to any specified place)

(1) ConsoleAppender options

  • Threshold=WARN: Specifies the minimum output level of log information. The default is DEBUG.
  • ImmediateFlush=true: indicates that all messages will be output immediately. If it is set to false, it will not be output. The default value is true.
  • Target=System.err: the default value is system out.

(2) FileAppender options

  • Threshold=WARN: Specifies the minimum output level of log information. The default is DEBUG.
  • ImmediateFlush=true: indicates that all messages will be output immediately. If it is set to false, it will not be output. The default value is true.
  • Append=false: true indicates that the message is added to the specified file. False overwrites the content of the specified file. The default value is true.
  • File=D:/logs/logging.log4j: Specifies that the message is output to logging Log4j file.

(3) DailyRollingFileAppender option

  • Threshold=WARN: Specifies the minimum output level of log information. The default is DEBUG.
  • ImmediateFlush=true: indicates that all messages will be output immediately. If it is set to false, it will not be output. The default value is true.
  • Append=false: true indicates that the message is added to the specified file. False overwrites the content of the specified file. The default value is true.
  • File=D:/logs/logging.log4j: Specifies that the current message is output to logging Log4j file.
  • DatePattern=’.' Yyyy mm: scroll the log file once a month, that is, generate a new log file every month. The log file name of the current month is logging Log4j, the log file name of the previous month is logging log4j. yyyy-MM.
    In addition, you can specify to scroll log files by week, day, hour, minute, etc. the corresponding format is as follows:
  1. '.' yyyy mm: Monthly
  2. '.' yyyy WW: Weekly
  3. '.' yyyy MM DD: every day
  4. '.' yyyy-MM-dd-a: twice a day
  5. '.' yyyy MM DD HH: per hour
  6. '.' yyyy MM DD HH mm: per minute

(4) RollingFileAppender option

  • Threshold=WARN: Specifies the minimum output level of log information. The default is DEBUG.
  • ImmediateFlush=true: indicates that all messages will be output immediately. If it is set to false, it will not be output. The default value is true.
  • Append=false: true indicates that the message is added to the specified file. False overwrites the content of the specified file. The default value is true.
  • File=D:/logs/logging.log4j: Specifies that the message is output to logging Log4j file.
  • MaxFileSize=100KB: the suffix can be KB, MB or GB. When the log file reaches this size, it will automatically scroll, that is, move the original content to logging log4j. 1 in the document.
  • MaxBackupIndex=2: Specifies the maximum number of scrolling files that can be generated. For example, setting it to 2 can generate logging log4j. 1,logging.log4j.2 two scrolling files and a logging Log4j file.

2.3 configure the output format of log information (Layout)

log4j.appender.appenderName.layout=className

className: the following values can be set:

  • (1)org.apache.log4j.HTMLLayout (layout in HTML table form)
  • (2)org.apache.log4j.PatternLayout (layout mode can be specified flexibly)
  • (3)org.apache.log4j.SimpleLayout (contains the level and information string of log information)
  • (4)org.apache.log4j.TTCCLayout (including log generation time, thread, category, etc.)

(1) HTMLLayout options

  • LocationInfo=true: output the java file name and line number. The default value is false.
  • Title=My Logging: the default value is Log4J Log Messages.

(2) PatternLayout options:

ConversionPattern=%m%n: sets the format in which messages are displayed.
Format symbol description:

  • %p: Priority of output log information, i.e. DEBUG, INFO, WARN, ERROR, FATAL.
  • %d: Output the date or time of the log time point. The default format is ISO8601. You can also specify the format after it, such as:% d{yyyy/MM/dd HH:mm:ss,SSS}.
  • %r: Output the number of milliseconds spent from application startup to outputting the log information.
  • %t: Output the name of the thread that generated the log event.
  • %l: The occurrence location of the output log event is equivalent to the combination of% 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: The category to which the output log information belongs is usually the full name of the class.
  • %M: Output the name of the method that generates log information.
  • %F: The name of the file where the output log message is generated.
  • %50: : the line number in the output code.
  • %m: : output the specific log information specified in the code.
  • %n: Output a carriage return line feed character, which is "\ r\n" for Windows platform and "\ n" for Unix platform.
  • %x: Output the NDC (nested diagnostic environment) associated with the current thread, especially for multi client and multi-threaded applications such as java servlets.
  • %%: output a '%' character.

In addition, you can add modifiers between% and format characters to control their minimum length, maximum length, and text alignment. For example:

    1. c: Specify the name of the output category. The minimum length is 20. If the name length of the category is less than 20, it is aligned right by default.
  • 2)%-20c: "-" indicates left alignment.
  • 3)%.30c: Specifies the name of the output category. The maximum length is 30. If the name length of the category is greater than 30, the extra characters on the left will be truncated, but if it is less than 30, no spaces will be filled.

Attachment: Log4j relatively comprehensive configuration

Log4j configuration file realizes a full set of functions such as outputting to console, file, rollback file, sending log mail, outputting to database log table, custom label and so on.

log4j.rootLogger=DEBUG,console,dailyFile,im
log4j.additivity.org.apache=true
# 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
log4j.appender.console.layout.ConversionPattern=[%-5p] %d(%r) --> [%t] %l: %m %x %n
# Log file (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
log4j.appender.logFile.layout.ConversionPattern=[%-5p] %d(%r) --> [%t] %l: %m %x %n
# Rolling 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
log4j.appender.rollingFile.layout.ConversionPattern=[%-5p] %d(%r) --> [%t] %l: %m %x %n
# Periodically rollback log file (dailyFile)
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
log4j.appender.dailyFile.layout.ConversionPattern=[%-5p] %d(%r) --> [%t] %l: %m %x %n
# Apply to socket
log4j.appender.socket=org.apache.log4j.RollingFileAppender
log4j.appender.socket.RemoteHost=localhost
log4j.appender.socket.Port=5001
log4j.appender.socket.LocationInfo=true
# Set up for Log Factor 5
log4j.appender.socket.layout=org.apache.log4j.PatternLayout
log4j.appender.socket.layout.ConversionPattern=[%-5p] %d(%r) --> [%t] %l: %m %x %n
# Log Factor 5 Appender
log4j.appender.LF5_APPENDER=org.apache.log4j.lf5.LF5Appender
log4j.appender.LF5_APPENDER.MaxNumberOfRecords=2000
# Send log to specified message
log4j.appender.mail=org.apache.log4j.net.SMTPAppender
log4j.appender.mail.Threshold=FATAL
log4j.appender.mail.BufferSize=10
log4j.appender.mail.From = xxx@mail.com
log4j.appender.mail.SMTPHost=mail.com
log4j.appender.mail.Subject=Log4J Message
log4j.appender.mail.To= xxx@mail.com
log4j.appender.mail.layout=org.apache.log4j.PatternLayout
log4j.appender.mail.layout.ConversionPattern=[%-5p] %d(%r) --> [%t] %l: %m %x %n
# Apply to 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.PatternLayout
log4j.appender.database.layout.ConversionPattern=[%-5p] %d(%r) --> [%t] %l: %m %x %n

# Custom Appender
log4j.appender.im = net.cybercorlin.util.logger.appender.IMAppender
log4j.appender.im.host = mail.cybercorlin.net
log4j.appender.im.username = username
log4j.appender.im.password = password
log4j.appender.im.recipient = corlin@cybercorlin.net
log4j.appender.im.layout=org.apache.log4j.PatternLayout
log4j.appender.im.layout.ConversionPattern=[%-5p] %d(%r) --> [%t] %l: %m %x %n

Attachment: output independent log file

There is no doubt about the powerful function of log4j, but it is inevitable that a function needs to output an independent log file in practical application. How can the required content be separated from the original log to form a separate log file? In fact, this function can be easily realized with a little configuration on the basis of the existing log4j.

common

Let's start with a common log4j Properties file, which is in the console and myweb Log in the log file:

log4j.rootLogger=DEBUG, stdout, logfile
 
log4j.category.org.springframework=ERROR
log4j.category.org.apache=INFO
 
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n

log4j.appender.logfile=org.apache.log4j.RollingFileAppender
log4j.appender.logfile.File=${myweb.root}/WEB-INF/log/myweb.log
log4j.appender.logfile.MaxFileSize=512KB
log4j.appender.logfile.MaxBackupIndex=5
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n

Different classes output different files

If you want to output different files for different classes (take cn.com.Test as an example), you must first run test Defined in Java:

private static Log logger = LogFactory.getLog(Test.class);
  Then in log4j.properties Add in:
log4j.logger.cn.com.Test= DEBUG, test
log4j.appender.test=org.apache.log4j.FileAppender
log4j.appender.test.File=${myweb.root}/WEB-INF/log/test.log
log4j.appender.test.layout=org.apache.log4j.PatternLayout
log4j.appender.test.layout.ConversionPattern=%d %p [%c] - %m%n
  That is, let cn.com.Test Medium logger use log4j.appender.test Configuration made.

Output multiple log files of the same type

But what if you need to output multiple log files in the same class? In fact, the truth is the same, first in test Defined in Java:

private static Log logger1 = LogFactory.getLog("myTest1");private static Log logger2 = LogFactory.getLog("myTest2");

Then in log4j Properties:

log4j.logger.myTest1= DEBUG, test1log4j.appender.test1=org.apache.log4j.FileAppenderlog4j.appender.test1.File=${myweb.root}/WEB-INF/log/test1.loglog4j.appender.test1.layout=org.apache.log4j.PatternLayoutlog4j.appender.test1.layout.ConversionPattern=%d %p [%c] - %m%n  log4j.logger.myTest2= DEBUG, test2log4j.appender.test2=org.apache.log4j.FileAppenderlog4j.appender.test2.File=${myweb.root}/WEB-INF/log/test2.loglog4j.appender.test2.layout=org.apache.log4j.PatternLayoutlog4j.appender.test2.layout.ConversionPattern=%d %p [%c] - %m%n```   	That is, in use logger Give it a custom name(As here"myTest1"),Then in log4j.properties Make corresponding configuration in. Don't forget to use different logs logger(If output to test1.log I want to use it logger1.info("abc")).   	Another problem is that these custom**By default, logs are output to both log4j.rootLogger In the configured log**,How can I only output them to the log specified by myself? Don't worry, here's a switch:    log4j.additivity.myTest1 = false        It is used to set whether to output to log4j.rootLogger In the configured log, set to false It won't be exported to other places! Pay attention here"myTest1"You gave it in the program logger The custom name! If you say, I just don't want to output this log to log4j.rootLogger Configured logfile In, stdout I also want to output it at the same time! That's easy. Put your log4j.logger.myTest1 = DEBUG, test1 Change to the following formula OK la log4j.logger.myTest1=DEBUG, test1