Log4j.properties Configuring and loading applications

Source: Internet
Author: User

Log4j.properties Summary:

First, Introduction
LOG4J is an Apache open source project, through the use of log4j, we can control the log information delivery destination is the console, files, GUI components, even the socket server, NT Event recorder, UNIX syslog daemon, etc. We can also control the output format of each log, and 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 the log information, the output destination of the log information, and the output format of the log information. The priority of log information is high to low with error, WARN, INFO, DEBUG, respectively, 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 the file, and the output format controls the display of the log information.

Second, the configuration file
In fact, you can also configure the LOG4J environment in your code without using the configuration file at all. However, using a configuration file will make your application more flexible.
LOG4J supports two configuration file formats, one in XML format and one in the properties format. Here's how to use the properties format as a 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, whose syntax is:
Log4j.rootlogger = [level], Appendername, Appendername, ...
Level is the priority of logging, which is divided into off, FATAL, ERROR, WARN, INFO, DEBUG, all, or levels you define. LOG4J recommends using only four levels, with the priority from high to low being error, WARN, INFO, DEBUG. By defining the level here, you can control the switch to the appropriate level of log information in your application. For example, if the info level is defined here, the log information for all debug levels in the application will not be printed.
Appendername is where you specify where the log information is exported. 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, LOG4J provides the following types of Appender:
Org.apache.log4j.ConsoleAppender (console),
Org.apache.log4j.FileAppender (file),
Org.apache.log4j.DailyRollingFileAppender (generates a log file every day),
Org.apache.log4j.RollingFileAppender (creates a new file when the file size reaches the specified size),
Org.apache.log4j.WriterAppender (send log information in stream format to any specified location)
(1). Consoleappender Options
Threshold=warn: Specifies the lowest level of output for log messages.
Immediateflush=true: The default value is true, meaning that all messages will be output immediately.
Target=system.err: By default: System.out, specify output console
(2). Fileappender Options
Threshold=warn: Specifies the lowest level of output for log messages.
Immediateflush=true: The default value is true, meaning that all messages will be output immediately.
File=mylog.txt: Specifies the message output to the Mylog.txt file.
Append=false: The default value is True, the message is added to the specified file, and false refers to overwriting the message with the specified file content.
(3). Dailyrollingfileappender Options
Threshold=warn: Specifies the lowest level of output for log messages.
Immediateflush=true: The default value is true, meaning that all messages will be output immediately.
File=mylog.txt: Specifies the message output to the Mylog.txt file.
Append=false: The default value is True, the message is added to the specified file, and false refers to overwriting the message with the specified file content.
Datepattern= '. ' YYYY-WW: Scrolls a file once a week, which results in a new file every week. You can also specify monthly, weekly, Days, hours, and minutes. 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: two times a day
5) '. ' YYYY-MM-DD-HH: Per hour
6) '. ' YYYY-MM-DD-HH-MM: Per minute
(4). Rollingfileappender Options
Threshold=warn: Specifies the lowest level of output for log messages.
Immediateflush=true: The default value is true, meaning that all messages will be output immediately.
File=mylog.txt: Specifies the message output to the Mylog.txt file.
Append=false: The default value is True, the message is added to the specified file, and false refers to overwriting the message with 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 to move the original content to the Mylog.log.1 file.
maxbackupindex=2: Specifies the maximum number of scroll files that can be produced.

3. Configure the layout of the log information with the following syntax:
Log4j.appender.appenderName.layout = Fully.qualified.name.of.layout.class
Log4j.appender.appenderName.layout.option1 = value1
...
Log4j.appender.appenderName.layout.option = Valuen
Among them, log4j offers the following types of layout:
Org.apache.log4j.HTMLLayout (Layout in HTML table Form),
Org.apache.log4j.PatternLayout (flexibility to specify layout mode),
Org.apache.log4j.SimpleLayout (contains the level of log information and the information string),
Org.apache.log4j.TTCCLayout (contains information about the time, thread, category, etc.) of the log

4. Output format Settings
The log output format can be set through Log4j.appender.A1.layout.ConversionPattern in the configuration file.
Parameters:
%p: Output log information priority, i.e. Debug,info,warn,error,fatal,
%d: the date or time of the output log time, the default format is ISO8601, can also be specified after the format, such as:%d{yyy MMM dd hh:mm:ss,sss}, output similar: October 18, 2002 22:10:28,921
%r: The number of milliseconds to output the log information from the application boot to output
%c: The class in which the output log information belongs, usually the full name of the class in which it is located
%t: Output The name of the thread that generated the log event
%l: The location of the output log event, which corresponds to the combination of%c.%m (%f:%l), including the class name, the thread that occurred, and the number of rows in the code. Example: Testlog4.main (testlog4.java:10)
%x: The NDC (nested diagnostic environment) associated with the output and current line threads, especially for multi-client multithreaded applications such as Java Servlets.
Percent: Output a "%" character
%F: The name of the file where the output log message was generated
%l: Line numbers in the output code
%M: The specified message in the output code, resulting in the log specific information
%n: Output a carriage return line break, Windows platform is "\ r \ n", Unix platform for "\ n" Output log information line-wrapping
You can add modifiers between% and pattern characters to control their minimum width, maximum width, and text alignment. Such as:
1)%20c: Specify the name of the output category, the minimum width is 20, if the category name is less than 20, the default is the right alignment.
2)%-20c: Specify the name of the output category, the minimum width is 20, if the category name is less than 20, the "-" number specifies left-aligned.
3)%.30c: Specify the name of the output category, the maximum width is 30, if the category name is greater than 30, will be the left more than the character of the cut off, but less than 30, there will be no spaces.
4)%20.30c: If the category name is less than 20, fill in the blanks, and right-aligned, if its name is longer than 30 characters, it is exported from the left hand-sold characters are truncated.

Iii. Loading log4j.properties files

1, Spring mode loading, configuration and Web. XML:

Spring load Log4j.properties, which provides a log4jconfiglistener that itself can load log4j configuration files and log4j output paths from a specified location via the Web. XML configuration, note that

Log4jconfiglistener must be before spring's listener.

Xml

<!--set the LOG4J profile location loaded by SPRNG--

<context-param>

<param-name>log4jConfigLocation</param-name>

<param-value>WEB-INF/classes/log4j.properties</param-value>

</context-param>

<!--spring refreshes the interval of log4j configuration file changes 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, can be through the resource class to load the resource file, and use as a whole

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 " );
}
}

Four, use in a program
before you use log4j in your program, The first step is to import Commons-logging.jar and Logging-log4j-1.2.9.jar into classpath and place the log4j.properties in the SRC root directory. Then you can use it.

1. Get logger
using log4j, the first step is to get the logger, which will be responsible for controlling the log information. The syntax is:
public static Logger GetLogger (String name),
Gets the logger by the specified name, and, if necessary, a new logger for that name. Name generally takes the name of this class, for example:
static Logger Logger = Logger.getlogger (ServerWithLog4j.class.getName ());
Note: It is recommended to use commons-logging with log4j for logging
private static Log logger = Logfactory.getlog ( Yourclass.class);

2. Inserting record information (formatting log information)
when the two necessary steps are completed, You can easily use logging statements of different priority levels to be inserted anywhere you want the log to be, with the following syntax:
Logger.debug (Object message);
Logger.info (Object message);
Logger.warn (Object message);
Logger.error (Object message);

For example:

org.apache.log4j.*; Logtest ... {Logger Logger = Logger.getlogger (logtest..)          GetName ()); Main (string[] args) ... {//Log4j.properties file is loaded via Propertyconfigurator, if this sentence is not added, there is spring loaded propertyconfigurator.configure (". \SRCLOG4J.P           Roperties "); Logger.debug (" Debug ... ");           Logger.info ("info ...");           Logger.warn ("Warn ...");      Logger.error ("error ..."); } }

Log4j.properties Configuring and loading applications

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.