log4j.properties summary:
1. Introduction
Log4j is an open source project of Apache. By using Log4j, we can control the destination of log information delivery to console, files, GUI components, even socket servers, NT event loggers, UNIX Syslog daemons, etc.; we can also control the output format of each log; by defining the level of each log information, we can control the log generation process more carefully.
Log4j consists of three important components: the priority of log information, the output destination of log information, and the output format of log information. The priority of log information is from high to low. ERROR, WARN, INFO, and DEBUG, which are used to specify the importance of this log information; the output destination of the log information specifies whether the log will be printed to the console or file; and the output format controls the display content of the log information.
2. Configuration file
In fact, you can also not use configuration files at all, but configure the Log4j environment in your code. However, using configuration files will make your application more flexible.
Log4j supports two configuration file formats, one is an XML format file and the other is a properties format file. Below we introduce the method of using properties format as configuration file:
Example:
log4j.rootLogger=INFO, A1 log4j.appender.A1=org.apache.log4j.ConsoleAppender log4j.appender.A1.layout=org.apache.log4j.PatternLayout log4j.appender.A1.layout.ConversionPattern=%-4r %-5p [%t] %37c %3x - %m%n
1. Configure the root logger, its syntax is:
log4j.rootLogger = [ level ] , appenderName, appenderName, …
Among them, level is the priority of logging, divided into OFF, FATAL, ERROR, WARN, INFO, DEBUG, ALL or the level you define. 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. You can specify multiple output destinations at the same time.
2. Configure the log information output destination Appender, whose syntax is:
log4j.appender.appenderName = fully.qualified.name.of.appender.class log4j.appender.appenderName.option1 = value1 … log4j.appender.appenderName.option = valueN
Among them, the appenders provided by Log4j are as follows:
org.apache.log4j.ConsoleAppender (Console), org.apache.log4j.FileAppender (File), org.apache.log4j.DailyRollingFileAppender (Create a log file every day), org.apache.log4j.RollingFileAppender (Create a new file when the file size reaches the specified size), org.apache.log4j.WriterAppender (Send log information in stream format to any specified place)
(1).ConsoleAppender Option
Threshold=WARN: Specifies the lowest level of output of log messages. ImmediateFlush=true: The default value is true, which means that all messages will be output immediately. Target=System.err: By default, it is: System.out, specify the output console
(2).FileAppender Options
Threshold=WARN: Specifies the lowest level of output of log messages.
ImmediateFlush=true: The default value is true, which means that all messages will be output immediately.
File=mylog.txt: Specifies that the message is output to the mylog.txt file.
Append=false: The default value is true, which means adding the message to the specified file. False means overwriting the message to the specified file content.
(3).DailyRollingFileAppender option
Threshold=WARN: Specifies the lowest level of output of log messages.
ImmediateFlush=true: The default value is true, which means that all messages will be output immediately.
File=mylog.txt: Specifies that the message is output to the mylog.txt file.
Append=false: The default value is true, which means adding the message to the specified file. False means overwriting the message to the specified file content.
DatePattern='.'yyyy-ww: Scroll the file once a week, that is, generate a new file every week. Of course, you can also specify monthly, week, day, time and minute. 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
Threshold=WARN: Specifies the lowest level of output of log messages.
ImmediateFlush=true: The default value is true, which means that all messages will be output immediately.
File=mylog.txt: Specifies that the message is output to the mylog.txt file.
Append=false: The default value is true, which means adding the message to the specified file. False means overwriting the message to the specified file content.
MaxFileSize=100KB: The suffix can be KB, MB or GB. When the log file reaches this size, it will automatically scroll, and the original content will be moved to
mylog.log.1 file.
MaxBackupIndex=2: Specifies the maximum number of scroll files that can be generated.
3. Configure the layout of log information, and its syntax is:
log4j.appender.appenderName.layout = fully.qualified.name.of.layout.class
log4j.appender.appenderName.layout.option1 = value1
…
log4j.appender.appenderName.layout.option = valueN
Among them, the layout provided by Log4j is as follows:
org.apache.log4j.HTMLLayout (layout in HTML table form),
org.apache.log4j.PatternLayout (the layout mode can be flexibly specified),
org.apache.log4j.SimpleLayout (contains the level and information string of log information),
org.apache.log4j.TTCCLayout (including time, thread, category, etc. of log generation)
4. Output format settings
In the configuration file, you can set the log output format through log4j.appender.A1.layout.ConversionPattern.
parameter:
%p: The output log information priority, i.e. DEBUG, INFO, WARN, ERROR, FATAL,
%d: The date or time of the log time point is output. The default format is ISO8601. You can also specify the format afterwards, such as: %d{yyy MMM dd HH:mm:ss, SSS}, the output is similar: October 18, 2002 22:10:28, 921
%r: The number of milliseconds to output from the application startup to the output of this log information
%c: The category to which the output log information belongs is usually the full name of the class
%t: Output the thread name that generates the log event
%l: The output log event occurs at the location of the occurrence of %C.%M (%F:%L), including the category name, the occurrence thread, and the number of lines in the code. Example: Testlog4.main(TestLog4.Java:10)
%x: The output of NDC (Nested Diagnostic Environment) associated with the current thread, especially in applications such as Java servlets with multi-customer and multi-threading.
%%: Output a "%" character
%F: The file name where the output log message was generated
%L: Line number in output code
%m: The message specified in the output code and the specific log information generated
%n: Output a carriage return line break, Windows platform is "/r/n", and Unix platform is "/n" to output log information line break
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 right. If its name is longer than 30 characters, cut off the characters that are intercepted from the left.
3. Load the log4j.properties file
1. Loading in spring mode, configuration and in web.xml:
Spring loads log4j.properties, which provides a Log4jConfigListener, which can load the log4j configuration file and log4j output path from the specified location through web.xml configuration. It should be noted that
Log4jConfigListener must be before Spring's Listener.
web.xml
<!-- Set the location of the Log4j configuration file loaded by Sprng --><context-param> <param-name>log4jConfigLocation</param-name> <param-value>WEB-INF/classes/log4j.properties</param-value> </context-param> <!-- The interval for Spring to refresh the Log4j configuration file to change in milliseconds --><context-param> <param-name>log4jRefreshInterval</param-name> <param-value>10000</param-value> </context-param> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener>
2. The resource file can be loaded through the resource class, and it is integrated with the use.
public class TestLog4j { public static void main(String[] args) { PropertyConfigurator.configure( " D:/Code/conf/log4j.properties " ); Logger logger = Logger.getLogger(TestLog4j. class ); logger.debug( " debug " ); logger.error( " error " ); } }4. Use in the program
Before using Log4j in the program, you must first import commons-logging.jar and logging-log4j-1.2.9.jar into the classpath and place log4j.properties in the src root directory. It will be ready to use next.
1. Get the recorder
Using Log4j, the first step is to obtain the log recorder, which will be responsible for controlling the log information. The syntax is:
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 () ) ;
Note: It is recommended to use commons-logging combined with log4j for logging
private static Log logger = LogFactory.getLog(Yourclass.class);
2. 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 ) ; Logger.info ( Object message ) ; Logger.warn ( Object message ) ; Logger.error ( Object message ) ;
For example:
import org.apache.log4j.*; public class LogTest ...{ static Logger logger = Logger.getLogger(LogTest.class.getName()); public static void main(String[] args) ...{ //Load the log4j.properties file through PropertyConfigurator. If you do not add this sentence, there is spring loading PropertyConfigurator.configure ( "./srclog4j.properties"); logger.debug("Debug..."); logger.info("Info..."); logger.warn("Warn ..."); logger.error("Error ..."); } }Summarize
The above is the log4j.properties configuration and loading application introduced by the editor. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support to Wulin.com website!