Log4j code explanation

Source: Internet
Author: User
Log4j usage notes

Log4j is an open source project of Apache. By using log4j, programmers can control the destination of log information delivery, including the console, files, Gui components, and NT event recorder. They can also control the output format of each log, you can also define the level of each log to control the log generation process in greater detail. The following code is an example:

// Log4j
Public void log4jdemo ()
{
Logger logger = logger. getlogger (test. Class );

Filereader Fr = NULL;
Try
{
Fr = new filereader ("info.txt ");
Logger.info ("begin Read File ");
}
Catch (filenotfoundexception E)
{
Logger. Error ("file not found", e );
Try {
Fr. Close ();
} Catch (ioexception E1 ){

Logger. Error ("file not found", E1 );
}
}
}

Log4j composition:
Log4j consists of three important components: logger, appenders, and layout ).
Logger: controls which logging statements are enabled or disabled, and limits the log information. appenders specifies whether logs will be printed to the console or files; layout controls the display format of log information.

A ).Obtain or create a logger object:
Logger is specified as an object and is identified by a string class name. The logger name is case sensitive and has an inheritance relationship between names. The child name uses the parent name as the prefix and uses the dot ". ", for example, X. Y is X. y. z's father.
Root logger is the ancestor of all logger and has the following attributes:
1. It always exists.
2. It cannot be obtained by name.
Root logger can be obtained using the following statement:

Public static logger. getrootlogger ();

Or:

Public static logger. getlogger (class clazz)

Currently, calling logger. getlogger (class clazz) is the most ideal method for the ogger object.

B)Log Level
Each logger is assigned a log level to control the output of log information. Log levels are classified:
A: The highest level of off, used to close all log records.
B: Fatal indicates that every serious error event will cause the application to exit.
C: Error indicates that although an error event occurs, it still does not affect the system to continue running.
D: Warm indicates a potential error.
E: info generally focuses on the entire process of application running at the coarse granularity level.
F: Debug is generally used for fine-grained debugging, which is very helpful for debugging applications.
G: The lowest level of all, used to open all log records.

The above levels are defined in the org. Apache. log4j. level class. Only four levels are recommended for log4j. The priority ranges from high to low: error, warn, info, and debug. By using the log level, you can control the output of corresponding levels of log information in the application. For example, if the info level is B, all logs (such as debug) lower than info level in the application will not be printed.

Package log4j;

Import org. Apache. log4j. basicconfigurator;
Import org. Apache. log4j. level;
Import org. Apache. log4j. Logger;

Public class log4jtest {

Public static void main (string [] ARGs ){

Logger logger = logger. getlogger (log4jtest. Class );

// Use the default configuration information and do not need to write log4j. Properties
Basicconfigurator. Configure ();
// Set the log output level to info, which will overwrite the level set in the configuration file
Logger. setlevel (level. info );
// The following messages will be output
Logger.info ("this is an info ");
Logger. Warn ("This Is A Warn ");
Logger. Error ("this is an error ");
Logger. Fatal ("this is a fatal ");

}

}

C) appender at the output end
Appender is used to specify the location where the log information is output, and multiple output destinations can be specified at the same time. Log4j allows you to output information to many different output devices. A log output destination is called an appender.
Each logger can have one or more appender. Each appender represents the output destination of a log. You can use logger. addappender (appender APP) to add an appender for logger, or use logger. removeappender (appender APP) to delete an appender for logger.
Below are several common output destinations of log4j.
A: org. Apache. log4j. leleappender: Output log information to the console.
B: org. Apache. log4j. fileappender: Output log information to a file.
C: org. Apache. log4j. dailyrollingfileappender: outputs log information to a log file and outputs it to a new log file every day.
D: Org. apache. log4j. rollingfileappender: outputs log information to a log file and specifies the file size. When the file size reaches the specified size, the file is automatically renamed and a new file is generated.
E: org. Apache. log4j. writeappender: sends log information to any specified place in stream format.
F: org. Apache. log4j. JDBC. jdbcappender: outputs log information to the database through JDBC.
 
Log formatter Layout
There are three types:
Htmllayout: format the log output as an HTML table:
Simplelayout: formatted log output in a very simple way. It prints three items: Level-Information
Example: Info-Info
Patternlayout: format the log output based on the specified conversion mode, or use the default conversion mode if no conversion mode is specified.
The following code implements the simplelayout and fileappender programs.

Public static void main (string [] ARGs ){

Logger logger = logger. getlogger (log4jtest. Class );
Simplelayout layout = new simplelayout ();
// Htmllayout layout = new htmllayout ();
Fileappender appender = NULL;
Try
{
// Configure the output end to out.txt
Appender = new fileappender (layout, "out.txt", false );
} Catch (exception E)
{
}
Logger. addappender (appender); // Add the output end
Logger. setlevel (level) level. Debug); // overwrite the level in the configuration file
Logger. debug ("debug ");
Logger.info ("info ");
Logger. Warn ("Warn ");
Logger. Error ("error ");
Logger. Fatal ("Fatal ");
}

Log4j Configuration
Configuring the log4j environment refers to configuring the root logger, including the logger level, appender for it, and layout for these appender. Because all other logger are descendants of the root logger, they all inherit the nature of the root logger. These can be done implicitly by setting system properties, or explicitly by calling xxxconfigurator. Configure () in a program. You can configure log4j in the following ways.
A: Put the configuration in the file, pass the file name and other information through the environment variables, and parse and configure the configuration using the default initialization process of log4j.
B: The configuration is stored in a file. The application server configuration is used to transmit information such as the file, and a specific servlet is used to complete the configuration.
C: Call the basicconfigor. Configure () method in the program.
D: Put the configuration in the file. Use the command line propertyconfigurator. Configure (ARGs []) to parse the log4j. properties file and configure log4j.
The following describes the methods basicconfigurator. Configure () and propertyconfigurator. config () respectively.
Basicconfigurator. Configure () method:
It uses a simple method to configure the log4j environment. The task completed by this method is:
1: Create a patternlayout object using the default method P:
Patternlayout P = new patternlayout ("%-4r [% T] %-5 p % C % x-% m % N ");
2: Use P to create leleappender object A with the target system. Out. standard output device:
Leleappender A = new cpnsoleappender (p, consoleappender. system_out );
3: Add a leleappender P for the root logger;
Rootlogger. addappender (P );
4: Set the Log Level of rootlogger to the dubug level;
Rootlogger. setlevel (level. Debug );

Propertyconfigurator. Configure () method:
When you use the following statement to generate a logger object:

Static logger = logger. getlogger (mycalss. Class );

If basicconfigurator. Configure (), propertyconfigurator. Configure () or domconfigurator. Configure () method is not called, log4j automatically loads the configuration file named log4j. properties under classpath. If you change the configuration file to another name, for example, my. properties, the program can still run, but a prompt is displayed that the log4j system cannot be correctly initialized. In this case, you can add:

Propertyconfigurator. Configure ("classes/My. properties ");

The problem can be solved.

Reprinted: http://www.cnblogs.com/eflylab/archive/2007/01/11/618001.html

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.