A log4j study-pencil count

Source: Internet
Author: User
Tags format constructor count reference throwable xmlns java web log4j
LOG4J Learning Notes

by Heavyz
2003-04-15

Turn from: http://zooo.51.net/heavyz_cs/notebook/log4j.html



--------------------------------------------------------------------------------





LOG4J Home: http://jakarta.apache.org/log4j



--------------------------------------------------------------------------------


Index

Class diagram of the log4j
Logger: Log writer
The output method of logger
Naming rules for Logger
Log level
Sample code
A two-point description of Logger
Appender: Log Destinations
Consoleappender
Fileappender
Rollingfileappender
Layout: Log Formatter
Patternlayout
Patterns in Patternlayout
Configuration: Configuring
The default log4j initialization process
Basicconfigurator.configure ()
Overview of log4j configuration files in XML format
Configuring Appender and layout in an XML file
My own simple example of using an XML file to configure a log4j environment
Log4j's coding habits
Resources



Class diagram of the log4j




Logger-log writer for programmers to output log information
Appender-Log destinations, output formatted log information to a specified location
Consoleappender-Destination for console Appender
Fileappender-Appender of the destination file
Rollingfileappender-Appender of a file with a destination size Limited
Layout-Log formatter, which is used to format the programmer's logging request into a string
Patternlayout-Format the logging request with the specified pattern layout



Logger: Log writer
The Logger object is used to replace the System.out or System.err log writer for the programmer to output log information.

The output method of logger
The Logger class object provides a series of methods for the programmer to output log information.




------log4j Apis:class Logger------



Printing methods:

public void Debug (Object msg);
public void Debug (Object msg, Throwable t);

public void info (Object msg);
public void info (Object msg, Throwable t);

public void warn (Object msg);
public void warn (Object msg, Throwable t);

public void error (Object msg);
public void error (Object msg, Throwable t);

public void Fatal (Object msg);
public void Fatal (Object msg, Throwable t);

Generic Printing method:

public void log (level L, Object msg);




Naming rules for Logger
Logger is identified by the name of a string class, and the logger name is case-sensitive and has an inherited relationship between the names, with the parent name as the prefix, and the dot number. For example: X.y is X.y.z's father.

A root logger (root logger) is the ancestor of all logger, which has the following attributes: 1 it always exists; 2 It cannot be obtained by name.

Get root Logger by calling public static Logger Logger.getrootlogger (); by calling public static Logger Logger.getlogger (String name) or the public static Logger Logger.getlogger (Class clazz) obtains (or creates) a named Logger. The latter is equivalent to calling Logger.getlogger (Clazz.getname ()).

In an object, call Logger.getlogger (class Clazz) with the class that the object belongs to to get the method that logger is considered to be the most sensible named logger that is currently known.


Log level
Each logger is assigned a log level, which is used to control the output of the log information. A logger that is not assigned a level inherits the level of its nearest parent logger.

Each output to logger log request (logging request) also has a level, and if the level of the request is greater than the level of the logger, the request is processed (called enabled) ; otherwise the request will be ignored. Therefore, we can learn that:

The lower the level of the logger, the more detailed the logger
The higher the level of logging request, which means that the logging request priority output

Five level definitions are predefined in the level class, and their size relationships are as follows:


Level.all < Level.debug < Level.info < Level.warn < Level.error < Level.fatal < Level.off




Sample code
The following code creates a logger with the class that it belongs to, enables the default configuration, sets its level and outputs several logging request.


Import Org.apache.log4j.Logger;
Import Org.apache.log4j.BasicConfigurator;
Import Org.apache.log4j.Level;

public class Log4jtest {
public static void Main (String argv[]) {


Create a logger by the name of Class Log4jtest.

Logger Logger = Logger.getlogger (Log4jtest.class);

Use the default configuration.

Basicconfigurator.configure ();

Set the logger level to Level.info

Logger.setlevel (Level.info);

This request would be disabled since Level.debug < Level.info.

Logger.debug ("This is Debug.");

These requests would be enabled.

Logger.info ("This is a info.");
Logger.warn ("This is a warning.");
Logger.error ("This is an error.");
Logger.fatal ("This is a fatal error.");

Return
}
}




A two-point description of Logger

Calling Logger.getlogger (String name) with a parameter with the same name returns a reference to the same logger. It is possible to configure logger in one place and get the logger in another place without passing logger references to each other.
Logger can be created in any order, that is, the parent logger can be created after the child logger. LOG4J will automatically maintain the logger inheritance tree.





Appender: Log Destinations
Each logger can have one or more appender, each of which represents the output destination of a log, such as a console or a file. You can add a appender to logger using Logger.addappender (Appender app); Logger.removeappender (Appender app) Removes a appender for logger.

By default, the logger additive flag is set to true, indicating that the child logger will inherit all appenders from the parent logger. This option can be reset to indicate that the child logger will no longer inherit the appenders of the parent logger.

Root logger owns the consoleappender with the target System.out, so by default all logger will inherit the Appender.




------log4j Apis:class Logger------



Adds or removes a Appender object for the Logger object:.

public void Appappender (Appender app);
public void Removeappender (Appender app);

Get and set the additive flag: whether to inherit the appenders of the parent logger:.
Note: When you set the additive flag to false, you must ensure that a new appender has been set for the logger:.
Otherwise log4j will error: Log4j:warn No appenders could be found for logger (x.y.z). :.

public boolean getadditivity ();
public void Setadditivity (Boolean additive);


Consoleappender
You can use the Consoleappender object to output logs to the console. Each consoleappender has a target that represents its output destination. It can be system.out, a standard output device (buffered display), or a system.err, standard error device (no buffer display). The use of Consoleappender is referenced by the following APIs:.




------log4j Apis:class Consoleappender extends writerappender------



Constructs a method that constructs a Consoleappender object using a Layout object:.
By default, the target of Consoleappender is System.out:.

Public Consoleappender (Layout Layout);

Constructs a method that constructs a Consoleappender object using a layout object and a target string:.
The possible values for Target are consoleappender.system_out and Consoleappender.system_err:.

Public Consoleappender (Layout Layout, String target);




Fileappender
You can use the Fileappender object to output the log to a specified log file. Use the method to refer to the following APIs:.




------log4j Apis:class Fileappender extends writerappender------



Constructs a method that constructs a Fileappender object using a Layout object and a log file name:.

Public Fileappender (Layout Layout, String filename)
Throws IOException;
Public Fileappender (Layout Layout, String filename, boolean append)
Throws IOException;




Rollingfileappender
You can use the Fileappender subclass Rollingfileappender object to output the log to a specified log file. The difference is that the log file is limited in size, and the file scrolls up (the oldest log is erased) when the content exceeds the maximum size. You can also specify how many backups to log files are made in the class object. Refer to the following API for specific use:.




------log4j Apis:class Rollingfileappender extends fileappender------



Constructs a method that constructs a Rollingfileappender object using a Layout object and a log file name:.

Public Rollingfileappender (Layout Layout, String filename)
Throws IOException;
Public Rollingfileappender (Layout Layout, String filename, boolean append)
Throws IOException;

Get and set the number of log backup files:.

public int getmaxbackupindex ();
public void Setmaxbackupindex (int index);

Gets and sets the maximum size of the scrolling log file:.

Public long getmaximumfilesize ();
public void Setmaximumfilesize (long size);






Layout: Log Formatter
Each appender is associated with a layout; The layout task is to format the user's logging Request,appender task is to send the layout formatted output to the specified destination.

Patternlayout
Patternlayout is a subclass of layout that controls the output format of the log using the format control string used in a C-language printf function. Use the following APIs for reference:.




------log4j Apis:class Patternlayout extends Layout------



The parameterless construction method uses Default_conversion_pattern to construct a patternlayout:.
Note: Default_conversion_pattern is "%m%n" and only message information is printed:.

public Patternlayout ();

Constructs a method that uses a custom pattern to construct a patternlayout:.

Public patternlayout (String pattern);

Gets and sets the log pattern for the Patternlayout object:.

Public String Getconversionpattern ();
public void Setconversionpattern (String pattern);




Patterns in Patternlayout
To be Continued




Configuration: Configuring
The configuration of the LOG4J environment is the configuration of the root logger, including the level at which the root logger is set, which appender to add to it, and so on. These can be done implicitly by setting the method of system properties, or by calling the Xxxconfigurator.configure () method in the program to do it explicitly.

The default log4j initialization process
The logger class's static initialization blocks (static initialization block) initialize the LOG4J environment by default. Note: If the programmer has configured the LOG4J environment by setting system properties, then the Xxxconfigurator.configure () method will not need to be explicitly invoked to configure the log4j environment.

The logger static initialization block examines a series of log4j-defined system properties when the initialization process is complete. The things it does are as follows:

Check the System Properties Log4j.defaultinitoverride, if the property is set to False, perform initialization, otherwise (otherwise, as long as it is not false, regardless of what value, or even no value, is not), skip initialization.
Assign the value of the system attribute log4j.configuration to the variable resource. If the system variable is not defined, the resource is assigned to "Log4j.properties". Note: It is a good idea to use the method of defining Log4j.configuration System properties in Apache's log4j documentation to set the default initialization file.
Attempts to convert the resource variable into a URL object URL. If the general conversion method does not work, call the Org.apache.log4j.helpers.Loader.getResource (resource, Logger.class) method to complete the transformation.
If the URL ends with ". html", the method Domconfigurator.configure (URL) is invoked to complete initialization, otherwise the method Propertyconfigurator.configure (URL) is invoked to complete initialization. If the resource specified by the URL cannot be obtained, the initialization process is jumped out.



Basicconfigurator.configure ()
The Basicconfigurator.configure () method configures the LOG4J environment using the minimalist approach. Note: Configuring the log4j environment means configuring root logger, because all other logger are descendants of root logger, so they (by default) inherit the nature of the root logger.

The tasks that basicconfigurator.configure () accomplish are:

Create Patternlayout object p with default pattern:
Patternlayout p = new Patternlayout ("%-4r[%t]%-5p%c%x-%m%n");
Create Consoleappender object A with P, target System.out, standard output device:
Consoleappender a = new Consoleappender (p,consoleappender.system_out);
Add a consoleappender p to root logger:
Rootlogger.addappender (P);
Set the log level of root logger to debug levels:
Rootlogger.setlevel (Level.debug);



Overview of log4j configuration files in XML format
XML-formatted log4j configuration files need to be read using the Org.apache.log4j.html.DOMConfigurator.configure () method. The syntax definition for an XML file can be found in the log4j release package: Org/apache/log4j/xml/log4j.dtd.

The tree structure of the log4j XML configuration file
The tree structure of the log4j XML configuration file is shown below, noting that the following figure shows only the parts that are commonly used. :.


XML declaration and DTD
|
Log4j:configuration
|
+--Appender (Name, Class)
| |
| +--param (name, value)
| +--layout (Class)
| |
| +--param (name, value)
+--Logger (name, additivity)
| |
| +--level (class, value)
| | |
| | +--param (name, value)
| +--Appender-ref (ref)
+--Root
|
+--param (Name, Class)
+--level
| |
| +--param (name, value)
+--Appender-ref (ref)




XML declaration and DTD
The header of an XML configuration file consists of two parts: an XML declaration and a DTD declaration. The format of the head is as follows:.


<?xml version= "1.0" encoding= "UTF-8"?>
<! DOCTYPE log4j:configuration SYSTEM "LOG4J.DTD" >




Log4j:configuration (root element)

xmlns:log4j [#FIXED attribute]: Define log4j namespace, take a fixed value "http://jakarta.apache.org/log4j/"
Appender [* Child]: A appender element defines a log output destination
Logger [* Child]: A logger element defines a log writer
Root [? Child]: The root element defines the root logger



Appender
The Appender element defines a log output destination.


name [#REQUIRED attribute]: Defines the name of the Appender so that it is referenced in the following text
class [#REQUIRED attribute]: Defines the full name of the class to which the Appender object belongs
param [* Child]: parameters passed to the class construction method when the Appender object is created
layout [? Child]: The layout object that the Appender uses



Layout
The layout element defines a log formatter that is associated with a appender.


class [#REQUIRED attribute]: Defines the full name of the class to which the layout object belongs
param [* Child]: parameters passed to the class construction method when the layout object is created



Logger
The logger element defines a log output.


name [#REQUIRED attribute]: Defines the name of the logger so that it is referenced in the following text
additivity [#ENUM attribute]: evaluates to "true" (default) or "false" to inherit the properties of the parent logger
levels [? Child]: Defines the log level of the logger
appender-ref [* Child]: Defines the output destination of the Logger



Root
The root element defines roots log output root logger.


param [* Child]: Arguments passed to the class construction method when the root logger object is created
levels [? Child]: Defines the log level for root logger
appender-ref [* Child]: Defines the output destination of the root logger



Level
The level element defines the log levels of the Logger object.


class [#IMPLIED attribute]: Defines the class to which the level object belongs, and by default is "Org.apache.log4j.Level class
value [#REQUIRED attribute]: Assigns a value to a Level object. Possible values from small to large in turn are "All", "Debug", "Info", "Warn", "error", "Fatal" and "off." A value of "off" indicates that no log information is being exported
param [* Child]: parameters passed to the class construction method when the level object is created



Appender-ref
The appender-ref element refers to the name of a appender element, adding a appender to the Logger object.


ref [#REQUIRED attribute]: A reference to the name of a appender element
Appender-ref element has no child elements



Param
The Param element provides arguments for the constructor method of the class when the object is created. It can be a child of elements such as appender, layout, filter, ErrorHandler, level, categoryfactory, and Root.


Name and value [#REQUIRED attributes]: A set of name value pairs that provide a parameter
param element has no child elements





Configuring Appender and layout in an XML file
Create different Appender objects or different layout objects to invoke different construction methods. You can use the Param child element to set different parameter values.

Creating Consoleappender Objects
The Consoleappender construction method does not accept other parameters. :.


... ... ... ...
<appender name= "Console.log" class= "Org.apache.log4j.ConsoleAppender" >
<layout ... >
... ...
</layout>
</appender>
... ... ... ...




Creating Fileappender Objects
You can pass two parameters for the constructor method of the Fileappender class: file represents the log file name, append indicates that if the file already exists, whether the log is appended to the end of the file, the value may be "true" and "false" (default). :.


... ... ... ...
<appender name= "File.log" class= "Org.apache.log4j.FileAppender" >
<param name= "File" value= "/tmp/log.txt"/>
<param name= "Append" value= "false"/>
<layout ... >
... ...
</layout>
</appender>
... ... ... ...




Creating Rollingfileappender Objects
In addition to file and append, you can pass two parameters for the constructor of the Rollingfileappender class: The number of Maxbackupindex backup log files (default is 1) ; MaxFileSize represents the maximum number of bytes allowed by the log file (10M is the default). :.


... ... ... ...
<appender name= "RollingFile.log" class= "Org.apache.log4j.RollingFileAppender" >
<param name= "File" value= "/tmp/rollinglog.txt"/>
<param name= "Append" value= "false"/>
<param name= "Maxbackupindex" value= "2"/>
<param name= "MaxFileSize" value= "1024"/>
<layout ... >
... ...
</layout>
</appender>
... ... ... ...




Creating Patternlayout Objects
You can pass parameter Conversionpattern for the Patternlayout class's construction method. :.


... ... ... ...
<layout class= "org.apache.log4j.patternlayout>
<param name= "Conversion" value= "%d [%t]%p-%m%n"/>
</layout>
... ... ... ...






My own simple example of using an XML file to configure a log4j environment
When developing a FAT client for Java Web start for a Wsota project, the following XML file was used to configure the LOG4J environment (file name is wsota-rc.log4j.html)::.


<?xml version= "1.0" encoding= "UTF-8"?>
<! DOCTYPE log4j:configuration SYSTEM "LOG4J.DTD" >

<log4j:configuration xmlns:log4j= "http://jakarta.apache.org/log4j/" >

<!--=================================================================-->
<!--a rolling file Appender-->
<!--=================================================================-->

<appender name= "Wsota-rc.file.log" class= "Org.apache.log4j.RollingFileAppender" >
<param name= "File" value= "/tmp/wsota-rc.log"/>
<param name= "Append" value= "false"/>
<layout class= "Org.apache.log4j.PatternLayout" >
<param name= "Conversionpattern" value= "%d [%t]%p-%m%n"/>
</layout>
</appender>

<!--=================================================================-->
<!--a console appender-->
<!--debug can be turned from setting level of root to "off"-->
<!--=================================================================-->

<appender name= "Wsota-rc.console.log" class= "Org.apache.log4j.ConsoleAppender" >
<layout class= "Org.apache.log4j.PatternLayout" >
<param name= "Conversionpattern" value= "%d [%t]%p-%m%n"/>
</layout>
</appender>

<!--turn on debug to a rolling file. -->

<root>
<level value= "Debug"/>
<appender-ref ref= "Wsota-rc.file.log"/>
</root>

<!--use the debug to console. \ turn -->
<!--
<root>
<level value= "Off"/>
<appender-ref ref= "Wsota-rc.console.log"/>
</root>
-->


<!--Use the turn off Debug. -->
<!--
<root>
<level value= "Off"/>
<appender-ref ref= "Wsota-rc.console.log"/>
</root>
-->

</log4j:configuration>


The following code is used in the FAT client program to configure the LOG4J environment using an external XML file, note that the Code field is in the static initialization block of the program's main class, and the class and XML configuration file containing the following code are in the same directory::.


Import Org.apache.log4j.html.DOMConfigurator;

public class Sapframe extends JFrame {
static {
Domconfigurator.configure (SapFrame.class.getResource ("wsota-rc.log4j.html"));
}
... ... ... ...
}






Log4j's coding habits

Let each class have a private static logger object that outputs all the log information in the class
Use an XML file to complete the configuration of the log4j environment. Place the configuration code for the LOG4J environment in the static initialization block in the main class of the project. Note: In a project, the log4j environment needs to be configured only once, not in every class that uses logger.
Creates a static logger object for the class with Myclass.class as a parameter
In addition ...



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.