Usage notes for log4j in Java

Source: Internet
Author: User

Using log4j, programmers can control the destination of log information delivery, including consoles, files, GUI components, and NT event loggers, as well as control the output format of each log, or control the log generation process more carefully by defining the level of each log message.

The composition of log4j:
The log4j consists of three important components: the logger (loggers), the output (appenders), and the log formatter (layout).
Logger: Controls which logging statements are enabled or disabled, with a level limit on log information: appenders Specifies whether the log will be printed to the console or the file, and layout controls the display format of the log information.

The composition of log4j:
The log4j consists of three important components: the logger (loggers), the output (appenders), and the log formatter (layout).
Logger: Controls which logging statements are enabled or disabled, with a level limit on log information: appenders Specifies whether the log will be printed to the console or the file, and layout controls the display format of the log information.

A). Logger the acquisition or creation of an object :
Logger is specified as an entity and is identified by the name of a string class. Logger's name is case sensitive, and the name has an inheritance relationship, and the child name is prefixed with the parent name, using the dot "." Separated, for example x.y was the father of x.y.z.
Root Logger (root Logger) is the ancestor of all Logger, and it has the following properties:
1. It's always there.
2. It cannot be obtained by name.
Root logger can be obtained using the following statement:

 Public Static Logger Logger.getrootlogger ();

Or:

 Public Static Logger Logger.getlogger (Class clazz)

Calling Logger.getlogger (Class clazz) is the ideal method for Ogger objects at this time.

B) log level
Each logger is logged at a log level to control the output of the log information. The log level is divided from high to Low:
a:off          highest level, which is used to turn off all log records.
b:fatal       indicates that each serious error event will cause the application to exit.
c:error       points out that although an error event occurs, it still does not affect the system's continued operation.
d:warm      indicates that a potential error condition occurs.
e:info          In general and at the coarse-grained level, the application is emphasized throughout the run.
f:debug      is generally used for fine-grained levels and is very helpful for debugging applications.
g:all           The lowest level for opening all log records. The

above levels are defined in the Org.apache.log4j.Level class. Log4j only recommends using 4 levels, with priority levels from high to low for Error,warn,info and debug respectively. By using the log level, you can control the output of the appropriate level of log information in your application. For example, if you use the info level B, all log information (such as Debug) in your application that is below the info level will not be printed.

 Packagelog4j;ImportOrg.apache.log4j.BasicConfigurator;ImportOrg.apache.log4j.Level;ImportOrg.apache.log4j.Logger; Public classLog4jtest { Public Static voidMain (string[] args) {Logger Logger= Logger.getlogger (log4jtest.class); //using the default configuration information, do not need to write log4j.propertiesbasicconfigurator.configure (); //set the log output level to info, which overrides the level set in the configuration fileLogger.setlevel (Level.info); //the following message will be outputLogger.info ("This was an info"); Logger.warn ("This is a warn"); Logger.error ("This was an error"); Logger.fatal ("This is a fatal"); }}

C) output End Appender
The appender is used to specify where the log information is exported and multiple output destinations can be specified at the same time. LOG4J allows information to be exported to many different output devices, and a log information output destination is called a appender.
Each logger can have one or more appender, and each appender represents the output destination of a log. You can use Logger.addappender (Appender app) to add a Appender to logger, or you can use Logger.removeappender (Appender app) Deletes a appender for logger.
The following are some common output destinations for log4j.
A:org.apache.log4j.consoleappender: Output log information to the console.
B:org.apache.log4j.fileappender: Output log information to a file.
C:org.apache.log4j.dailyrollingfileappender: Output log information to a log file and output to a new log file daily.
D:org.apache.log4j.rollingfileappender: Output log information to a log file, and specify the size of the file, when the file size reaches the specified size, will automatically rename the file, and generate a new file.
E:org.apache.log4j.writeappender: Sends the log information in stream format to any specified place.
F::org.apache.log4j.jdbc.jdbcappender: Output log information to the database through JDBC.

Log Formatter layout
There are three kinds:
Htmllayout: The format log output is in HTML table Form: as shown in:

Simplelayout: Format the log output in a very simple way, it prints three items: level-information. such as: Info-info

Patternlayout:: Formats the log output according to the specified conversion mode, or uses the default conversion mode format if no conversion mode is specified.
The following code implements the Simplelayout and Fileappender programs.

 Public Static voidMain (string[] args) {Logger Logger= Logger.getlogger (log4jtest.class); Simplelayout Layout=Newsimplelayout (); //htmllayout layout = new Htmllayout ();Fileappender Appender =NULL; Try        {            //Configure the output to OUT.txtAppender =NewFileappender (Layout, "OUT.txt",false); }Catch(Exception e) {} logger.addappender (Appender);//Add output sideLogger.setlevel (level) level.debug);//overriding levels in a configuration fileLogger.debug ("Debug"); Logger.info ("Info"); Logger.warn ("Warn"); Logger.error ("Error"); Logger.fatal ("Fatal"); }

Configuration of the log4j
Configuring the log4j environment means configuring root Logger, including which level to Logger, which appender to add, and layout for these appender, and so on. Because all other logger are descendants of root logger, they all inherit the nature of root logger. These can be done implicitly by setting the system properties, or you can call the Xxxconfigurator.configure () method in your program to do so explicitly. There are several ways to configure the log4j.
A: The configuration is placed in the file, through the environment variables to pass the file name and other information, using the LOG4J default initialization process parsing and configuration.
B: The configuration is placed in the file, through the application server configuration to pass the file, such as the meadow, using a specific servlet to complete the configuration.
C: Call the Basicconfigurator.configure () method in the program.
D: The configuration is placed in the file, and the Log4j.properties file is parsed and configured log4j via command line Propertyconfigurator.configure (args[]).
The Basicconfigurator.configure () method and the Propertyconfigurator.config () method are described below respectively.
Basicconfigurator.configure () Method:
It uses a simple method to configure the log4j environment. The tasks that this method accomplishes are:
1: Create the Patternlayout object P in the default way:

  New Patternlayout ("%-4r[%t]%-5p%c%x-%m%n");

2: Create Consoleappender object A with P, Target is system.out, standard output device:

New Consoleappender (p,consoleappender.system_out);

3: Add a consoleappender p for root logger;

Rootlogger.addappender (a);

4: Set the log level of the Rootlogger to Dubug;

Rootlogger.setlevel (Level.debug);

Propertyconfigurator.configure () Method:

When you use the following statement to generate a logger object:

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

If you do not call the Basicconfigurator.configure (), propertyconfigurator.configure (), or Domconfigurator.configure () method, LOG4J automatically loads the configuration file named Log4j.properties under Classpath. If you change this profile to a different name, such as My.properties, the program still works, but it will report a hint that the log4j system could not be initialized correctly. This can be added in the program:

Propertyconfigurator.configure ("Classes/my.properties");

Problem can be solved.

Usage notes for log4j in Java

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.