Log4j Getting Started configuration and component detailed

Source: Internet
Author: User
Tags custom name truncated log4j

Log4j is an open source project for Apache, by using log4j, we can control the destination (console, file, GUI component, even interface server) of the log information, we can control the output format of each log, by defining the level of each log information, We are able to control the log generation process in more detail. Most interesting of all, these can be configured flexibly with a single configuration file without the need to modify the applied code. -Baidu Encyclopedia One, log4j basic usage 1. Add log4j Dependencies (add log4j package)

<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.16</version>
</dependency>
2. Create logger objects in related business classes 2.1 There are two ways to create logger objects, the first of which is created from the class object of the current classes.
public class UserService {

    ///Create Logger object public
    static final Logger with current class Logger = Logger.getlogger ( Userservice.class);

    public void Useradd () {
        //omitted content ...
    }
}
2.2 The second way is created by a custom name. (This method is not recommended)
public class UserService {

    ///Create Logger object public
    static final Logger with current class Logger = Logger.getlogger ("test");

    public void Useradd () {
        //omitted content ...
    }
}
3. Add the log output code to the business code

Depending on the importance of the log information in the system, select different levels of the Logger object to record, log4j will enter the corresponding log according to the log level configured in the configuration file (log4j.properties).

public void Useradd () {
    logger.debug ("Log debug level information ...");
    Logger.info ("Record info level information ...");
    Logger.warn ("Record warn level information ...");
    Logger.error ("Record error level information ...");
    Logger.fatal ("Record fatal level information ...");
}
4. Add log4j configuration file

The components in LOG4J are configured through a property file, The file defaults to Log4j.properties, the default path is in the SRC root, and in the Web project, the configuration file name and path are modified by adding the Log4jconfiglocation property to the Web.xml file. Modify log4j.properties file name and path in 4.1 web.xml

<context-param>
    <param-name>log4jconfiglocation</param-name >
    <param-value> Classpath:log4j.properties</param-value>
</context-param>
4.2 log4j.properties File Configuration Example
##### #配置输出日志的目录和输出日志的级别 ########## #rootLogger: Set the log of all logger objects configured under the output root (classpath) #第一个参数Debug: What level of log output? The second parameter stout: which appender to output (multiple Appender can be configured, such as: Df_debug,df_error) #log4j. Logger.cn.ship.log4j=warn,stout: The log with the Logger object configured under the output CN.SHIP.LOG4J package, if the log level under the specified package is less than Rootlogger, the log under the specified package is output #log4j at the current configuration level. Logger.test = Warn,stout:

Access based on logger name needs to be specified by name when creating the Logger object (see Create logger second form) ############################################# Log4j.rootlogger=debug,stout,df_debug,df_error log4j.logger.cn.ship.log4j=warn,stout log4j.logger.test = Warn, Stout ################# #控制台输出 ################## #log4j. Appender.stout: Specifies the log output in that manner (console mode), Stout for user-defined Appender name #log4j. Appender.stout.Target: Output in System.out mode, and can also use System.err # Log4j.appender.stout.layout: Specifies the layout mode of the current Appender log (currently selected Patternlayout mode) # Log4j.appender.stout.layout.ConversionPattern: Specifies the log format for the patternlayout mode ########################################## # # Log4j.appender.stout=org.apache.log4j.consoleappender Log4j.appender.stout.target=system.out Log4j.appeNder.stout.layout=org.apache.log4j.patternlayout log4j.appender.stout.layout.conversionpattern= [%5p]%d{ Yyyy-mm-dd hh:mm:ss,sss} method:%l%n%m%n ################# #滚动文件输出 (Debug level) ################## Log4j.appender.DF_ Debug=org.apache.log4j.dailyrollingfileappender Log4j.appender.DF_DEBUG. File=/home/ship/log/debug.log Log4j.appender.DF_DEBUG. Threshold=debug Log4j.appender.DF_DEBUG. Datepattern= '. ' Yyyy-mm-dd ' Log4j.appender.df_debug.layout=org.apache.log4j.patternlayout log4j.appender.DF_ Debug.layout.conversionpattern=%d{yyyy-mm-dd HH:MM:SS} [%t:%r]-[%p]%m%n ################# #滚动文件输出 (Error level) ######## ########## Log4j.appender.df_error=org.apache.log4j.dailyrollingfileappender Log4j.appender.DF_ERROR. File=/home/ship/log/error.log Log4j.appender.DF_ERROR. Threshold=error Log4j.appender.DF_ERROR. Datepattern= '. ' Yyyy-mm-dd ' Log4j.appender.df_error.layout=org.apache.log4j.patternlayout log4j.appender.DF_ Error.layout.conversionpattern=%d{yyyy-mm-dd HH:MM:SS} [%t:%r]-[%p]%m%n
Second, log4j components


The LOG4J structure diagram shows that log4j consists of three important components, namely, logger (log writer), log output terminal (Appender), log layout mode (Layout). One of the logger corresponds to multiple appender, and a appender contains a log layout pattern. 1. Log recorder (Logger)

Logger is mainly responsible for logging information, according to the importance of log information, logger objects are divided into the following log levels, from high to the end are:

Log Level Description
Off Highest level, used to turn off all log records
FATAL Indicates that each critical error event will cause the application to exit
ERROR Indicates that although an error event occurs, it still does not affect the continued permission of the system
WARN Indicates that a potential error situation may occur
INFO Typically used at a coarse-grained level, emphasizing the full operation of the application
DEBUG Typically used at fine-grained levels, which is very helpful for the debugger
All Lowest level, used to open all log records

LOG4J recommends using only four levels, from highest to lowest priority: ERROR, WARN, INFO, DEBUG. By defining the level here, you can control the corresponding level of log information in the application switch. 2. Log output terminal (Appender)

Appender is used to configure the destination of log information output, LOG4J provides several Appender objects:

Appender Objects Description
Org.apache.log4j.ConsoleAppender Enter to console
Org.apache.log4j.FileAppender Enter to File
Org.apache.log4j.DailyRollingFileAppender Enter to file (generate file by specified time)
Org.apache.log4j.RollingFileAppender Enter to file (generate file by specified file size)
Org.apache.log4j.WriterAppende Send log information to a specified location in a streaming manner
3. Log layout mode (Layout) 3.1 Layout is responsible for controlling the log information output format, LOG4J provides the following layout modes: of the object
Layout Objects description
Org.apache.log4j.HTMLLayout HTML Table Form Layout
Org.apache.log4j.PatternLayout Flexibility to customize layouts
Org.apache.log4j.SimpleLayout Simple layout of levels and message strings that contain log information
Org.apache.log4j.TTCCLayout Contains information about the time, thread, category, and so on that the log generated
3.2 If you are using Patternlayout mode, you can customize the log format by using the following parameters: The
parameter
%m Enter the message specified in the Code
%p output priority, that is, Debug,info,warn,error
%r output from the application boot to the number of milliseconds to output the log message
% c output belongs to the class, usually the full name of the class in which it is located
%t outputs the thread name that generated the log event
%n outputs a carriage return line break
%d outputs the date or time of the log point-in-time, the default format is ISO8601, or the format can be specified thereafter, such as%d{yyyy-mm-dd hh:mm:ss,sss}
% l outputs the location where the log event occurred, including the class name, the thread that occurred, and the function in code
%x output and the NDC (nested diagnostics environment) associated with the current line threads relative, especially with multiple client multi-threaded applications such as the Java servlet
% output a "%" character
% F output Log message when the file name is created
% L line number in output code
3.3 We can also control the minimum width, maximum width, and alignment by adding modifiers between the percent sign (%) and the pattern character, as follows:%20C: Specifies the name of the output category, the minimum width is 20, and the default right alignment if the category name is less than 20. %-20C: Specifies the name of the output category, the minimum width is 20, if the category name is less than 20 of the flowers, the "-" number specifies left-aligned. %.30C: Specifies the name of the output category, the maximum width is 30, if the category name is greater than 30, will be the left more characters truncated, but less than 30 words will not have spaces. %20.30C: If the name of the category is less than 20 to fill the space, and the right alignment, if its name is greater than 30, the left more characters will be truncated.

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.