1. Overview
1.1 Background
Logging is very important in our daily development. Adding logging in applications is generally based on three purposes: monitoring the changes in variables in the code, periodically recording them into files for statistical analysis by other applications; tracking the code runtime trajectory as the basis for future audits; acting as a debugger in the integrated development environment, printing code debugging information to the file or console.
1.2 Introduction
Log4j(log for java) is an open source project of Apache, which provides a delicate way to manage logs. Through a configuration file, we can control the output format and destination of each log with multiple choices. By defining the level of information, we can also flexibly switch feedback information in the code. Simply put, log4j is an API library that helps developers manage log output. Its most important feature is that the configuration file can flexibly set the priority of log information, the output destination of log information, and the output format of log information.
2.log4j configuration
2.1log4j class diagram
2.2 Defining the configuration file
Log4j can be dynamically set through Java programs. The obvious disadvantage of this method is: if you need to modify the log output level and other information, you must modify the java file and then recompile it, which is very troublesome.
Using configuration files will make our application more flexible to configure logs, and log output methods include output priority, output destination, and output format. Log4j supports two configuration file formats, one is an XML file, and the other is a Java feature file log4j.properties (key=value).
2.3 Configuration file log4j.properties
When Log4J is called for the first time, Log4J will locate the file in the classpath (../web-inf/class/ of course, as long as the directory is included in the classpath), and read the complete configuration of the file. This configuration file tells Log4J what format, what information to output to where it is. Correspondingly, we need to configure three aspects:
1. Root directory (level and destination);
2. Destination (console, file, etc.);
3. Output style (how to display log content)
Examples are as follows:
#Set log output level
log4j.rootLogger=debug,appender1
#Output to console
log4j.appender.appender1=org.apache.log4j.ConsoleAppender
#Style is TTCCLayout
log4j.appender.appender1.layout=org.apache.log4j.TTCCLayout
2.4. Log4j three components description
Log4j has three main components: Loggers, Appender (output source) and Layout (layout). Combining these three components allows easy logging of the type and level of information, and can control the style and location of log output at runtime. The following are the three components:
2.4.1 Logger Logger
The Logger object is used to replace System.out or System.err's log writer, which is used to provide programmers with log information output.
The root logger is configured with the syntax:
log4j.rootLogger = [ level ] , appenderName, appenderName,…
Among them, level is the priority of logging, divided into OFF, FATAL, ERROR, WARN, INFO, DEBUG, ALL or custom levels. Log4j recommends using only four levels, with priority from high to low, namely ERROR, WARN, INFO, and DEBUG. By the level defined here, you can control the switches to the corresponding level of log information in the application. For example, if the INFO level is defined here, all DEBUG level log information in the application will not be printed out. appenderName specifies where the log information is output to. Multiple output destinations can be specified simultaneously.
2.4.2 Output destination Appender
The Log4j log system allows log output to different places, such as console (Console), files (Files), new files are generated based on days or file size, and sent to other places in the form of streams, etc.
Configure appender, its syntax is expressed as:
log4j.appender.appenderName = fully.qualified.name.of.appender.classlog4j.appender.appenderName.option1 = value1…log4j.appender.appenderName.option = valueN
"fully.qualified.name.of.appender.class" can specify one of the following five destinations:
1).org.apache.log4j.ConsoleAppender (Console)
2).org.apache.log4j.FileAppender (file)
3).org.apache.log4j.DailyRollingFileAppender (generate one log file 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 Option
(2).FileAppender Options
(3).DailyRollingFileAppender option
That is, 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: Hourly
6)'.'yyyy-MM-dd-HH-mm: per minute
4.RollingFileAppender Options
2.4.3 Format (Layout) Layout
Sometimes I want to format my own log output according to my preferences. Log4j can attach a Layout behind the Appender to complete this function.
Configure Layout, its syntax is expressed as:
log4j.appender.appenderName.layout = fully.qualified.name.of.layout.classlog4j.appender.appenderName.layout.option1 = value1…log4j.appender.appenderName.layout.option = valueN
Layout provides four log output styles, as follows:
(1).org.apache.log4j.HTMLLayout (layout in HTML table form),
(2).org.apache.log4j.PatternLayout (the layout mode can be flexibly specified),
(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. information)
HTMLLayout Options
LocationInfo=true: The default value is false, output the java file name and line number
Title=my app file: The default value is Log4J Log Messages.
2. PatternLayout Options
ConversionPattern=%m%n: Specifies how to format the specified message.
What needs to be explained here is the meaning of several symbols in the log information format:
Modifiers can be added between % and pattern characters to control their minimum width, maximum width, and text alignment. like:
1)%20c: Specify the name of the output category, the minimum width is 20. If the name of the category is less than 20, it is right-aligned by default.
2)%-20c: Specifies the name of the output category, the minimum width is 20. If the name of the category is less than 20, the "-" sign specifies left alignment.
3)%.30c: Specify the name of the output category. The maximum width is 30. If the name of the category is greater than 30, the extra characters on the left will be cut off, but if they are less than 30, there will be no spaces.
4)%20.30c: If the name of category is less than 20, fill in the space and align it right. If its name is longer than 30 characters, cut off the extra characters from the left.
2.5.log4j configuration example
The simplicity of LOG4J configuration makes it spread across more and more applications: Log4J configuration files implement a complete set of functions such as output to the console, files, rollback files, sending log mail, output to database log tables, and custom tags.
log4j.rootLogger=DEBUG,CONSOLE,A1,im log4j.addivity.org.apache=true
n Apply to the console
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppenderlog4j.appender.Threshold=DEBUG log4j.appender.CONSOLE.Target=System.outlog4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout log4j.appender.CONSOLE.layout.ConversionPattern=%d-%c-%-4r[%t]%-5p%c%x-%m%n
n Apply to files
log4j.appender.FILE=org.apache.log4j.FileAppenderlog4j.appender.FILE.File=file.loglog4j.appender.FILE.Append=falselog4j.appender.FILE.layout=org.apache.log4j.PatternLayoutlog4j.appender.FILE.layout.ConversionPattern=%d - %c -%-4r [%t] %-5p %c %x - %m%n
n Apply to file rollback
log4j.appender.ROLLING_FILE=org.apache.log4j.RollingFileAppenderlog4j.appender.ROLLING_FILE.Threshold=ERRORlog4j.appender.ROLLING_FILE.File=rolling.loglog4j.appender.ROLLING_FILE.Append=truelog4j.appender.Append=truelog4j.append ender.ROLLING_FILE.MaxFileSize=10KBlog4j.appender.ROLLING_FILE.MaxBackupIndex=1log4j.appender.ROLLING_FILE.layout=org.apache.log4j.PatternLayoutlog4j.appender.ROLLING_FILE.layout.ConversionPattern=%d - %c -%-4r [%t] %-5p %c %x - %m%n
n Apply to socket
log4j.appender.SOCKET=org.apache.log4j.RollingFileAppenderlog4j.appender.SOCKET.RemoteHost=localhost log4j.appender.SOCKET.Port=5001log4j.appender.SOCKET.LocationInfo=true log4j.appender.SOCKET.layout=org.apache.log4j.PatternLayoutlog4j.appender.SOCET.layout.ConversionPattern=[start]%d{DATE}[DATE]%n%p[PRIORITY]%n%x[NDC]%n%t[THREAD]%n%c[CATEGORY]%n%m[MESSAGE]%n%n%n# Log Factor 5 Appender log4j.appender.LF5_APPENDER=org.apache.log4j.lf5.LF5Appender log4j.appender.LF5_APPENDER.MaxNumberOfRecords=2000n Send logs to email
log4j.appender.MAIL=org.apache.log4j.net.SMTPAppenderlog4j.appender.MAIL.Threshold=FATALlog4j.appender.MAIL.BufferSize=10log4j.appender.MAIL.From=web@www.wuset.comlog4j.appender.MAIL.SMTPHost=www.wusetu.comlog4j.appender.MAIL.Subject=Log4J Message log4j.appender.MAIL.To=web@www.wusetu.comlog4j.appender.MAIL.layout=org.apache.log4j.PatternLayout log4j.appender.MAIL.layout.ConversionPattern=%d-%c-%-4r[%t]%-5p%c%x-%m%n
n for database
log4j.appender.DATABASE=org.apache.log4j.jdbc.JDBCAppenderlog4j.appender.DATABASE.URL=jdbc:mysql://localhost:3306/testlog4j.appender.DATABASE.driver=com.mysql.jdbc.Driver log4j.appender.DATABASE.user=rootlog4j.appender.DATABASE.password=log4j.appender.DATABASE.sql=INSERT INTO LOG4J (Message) VALUES ('%d - %c -%-4r [%t] %-5p %c %x - %m%n')log4j.appender.DATABASE.layout=org.apache.log4j.PatternLayout log4j.appender.DATABASE.layout.ConversionPattern=%d-%c-%-4r[%t]%-5p%c%x-%m%nlog4j.appender.A1=org.apache.log4j.DailyRollingFileAppender log4j.appender.A1.File=SampleMessages.log4j log4j.appender.A1.DatePattern=yyyyMMdd-HH'.log4j'log4j.appender.A1.layout=org.apache.log4j.xml.XMLLayoutn Custom Appender
log4j.appender.im = net.cybercorlin.util.logger.appender.IMAppenderlog4j.appender.im.host = mail.cybercorlin.net log4j.appender.im.username = username log4j.appender.im.password = password log4j.appender.im.recipient = [email protected]=org.apache.log4j.PatternLayoutlog4j.appender.im.layout.ConversionPattern =[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n
3. Configure Log4j for SPRING in WEB application
First, you need to add the following configuration statement to the web.xml file:
<!-- To avoid conflicts between projects, define a unique webAppRootKey--> <context-param> <param-name>webAppRootKey</param-name> <param-value>myProject.root</param-value> </context-param> <!-- Load the configuration file log4j.properties --> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>/WEB-INF/classes/config/log4j/log4j.properties</param-value> </context-param> <!-- Set the time interval for refreshing the log configuration file, set to 60s here --> <context-param> <param-name>log4jRefreshInterval</param-name> <param-value>60000</param-value> </context-param> <!-- Load the log4j listener in the Spring framework Log4jConfigListener --> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener>
It is recommended to set the value of the property log4jConfigLocation to: /WEB-INF/classes/log4j.properties, so that when we do some tests, we can correctly record log information when we do not start the web application. Log4jConfigListener is a tool class provided by spring. It opens a log4j monitoring thread and detects log configuration changes every 60 seconds (log4jRefreshInterval variable definition), so that there is no need to restart the web service every time to apply the new configuration. In tomcat, no system properties are separated based on web applications. Therefore, a unique "webAppRootKey" must be defined for each web application, and we named it webApp.root. After starting the environment, Log4jConfigListener will inject the value into the webApp.root variable.
4. Use Log4j in the code
4.1. Get the recorder
Using Log4j, the first step is to obtain a log recorder, which will be responsible for controlling the log information.
public static Logger getLogger( String name)
Get the logger by the specified name and, if necessary, create a new logger for the name. Name is generally named in this class, such as:
static Logger logger = Logger.getLogger ( ServerWithLog4j.class.getName () )
4.2. Read the configuration file
After obtaining the logger, the second step will configure the Log4j environment, with the syntax as:
If you place log4j.properties in the root directory of the project, you can also not write this sentence, and the program will automatically find the configuration file.
BasicConfigurator.configure (): Automatically and quickly use the default Log4j environment. PropertyConfigurator.configure ( String configFilename ): Reads configuration files written using Java's feature files.
DOMConfigurator.configure ( String filename ): Read configuration files in XML form.
log4j is initialized using the above 3 configurators, and the use of PropertyConfigurator is suitable for all systems. The following statement.
PropertyConfigurator.configure("log4j.properties");For general java project, log4j can be initialized without using the above statement. log4j will automatically find the configuration file under classpath and initialize it. If log4j cannot automatically initialize the configuration file, then the above method needs to be initialized.
Note: When initializing the configuration file, it is best to execute it only once when the system starts. If it executes it multiple times, one is a waste of resources, and the other is that for the old version of log4j, problems may occur when using DailyRollingFileAppender.
4.3. Insert record information (format log information)
When the previous two necessary steps are completed, you can easily insert the logging statements of different priority levels anywhere you want to log. The syntax is as follows:
Logger.debug ( Object message ) ;