[Repost] log4j learning notes

xiaoxiao2021-03-06  14

Log4j learning notes

Submit: Mars Wednesday, 2004-12-15 17:09

Java related

By Heavyz2003-04-15

Log4J Homepage:

http://jakarta.apache.org/log4j

Index

Log4j class diagram Logger: log write

Logger's output method logger's naming rule log level sample code About Logger's two points for Logger Appender: log destination

ConsoleAppenderfileAppenderrollingFileAppenderLayout: Log formatter

PatternLayoutPatterns in PatternLayoutConfiguration: Configuration

Default log4j initialization process BasicConfigurator.configure () XML format Log4J Profile Overview Configuring Appender and Layout in XML File Irso Into an XML file Configuring Log4j Environment Very simple example log4j's code habits

Log4j class diagram

Logger - Log Writer for programmer output log information Appender - log destinations, output formatted log information to the specified place

ConsoleAppender - Destination for the appenderfileappender - destination for the appenderrollingfileAppender - the destination for the appenderLayout - log format of the size of the limited file, used to format the programmer's logging request to string

PatternLayout - Format Layout with the specified Pattern to logging Request

Logger: Log Writer Logger object is used to replace system.out or system.err log write utensils for programmers to output log information.

Logger's Output Method Logger class object provides a range of methods for programmers 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; Public VoID INFO 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);

Logger's naming rule logger is identified by a String class, and the name of the logger is sensitive, and the relationship between the names between the names, the child name has a parent name as a prefix, with a point number. Separate. Such as: x.y is the father of x.y.z. Root logger (root logger) is all ancestors of the Logger, which has the following properties: 1) It always exists; 2) It is not available through the name. Get root logger by calling public static logger.getrootLogger; obtains a named logger by calling public static logger logger.getlogger or public static logger logger.getlogger (Class Clazz). The latter is equivalent to calling Logger.getLogger (Clazz.getName ()). In an object, the class belonging to the object belongs as a parameter, calling the Logger.getLogger (Class Clazz) to get the Logger's method for named Logger, which is known. Log Level Each Logger is assigned a log level to control the output of log information. The Logger that is unassigned will inherit it will inherit its nearest parent Logger. Each output to the logger log request also has a Level, if the Request's Level is greater than equals the Logger's level, the request will be processed (called Enabled); otherwise the request will be ignored. Therefore, you can know:

The lower the Logger's Level, the higher the Logging Request's Level, the higher the Logging Request, and the Logging Request is predefined in the LEVEL class predefined five levels, and their size relationship is as follows: Level.all

Sample Code The following code will use the class you belong to the class as a parameter, create a logger, enable the default configuration, set its Level and output a number of logging requests to it.

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 Will Be Disabled Since Level.debug

"" "This is an error."); Logger.fatal ("this is a fatal error."); Return;}} 2 descriptions about Logger

Calling Logger.getLogger (String Name) with the same name parameters will return references to the same Logger. Therefore, you can configure the logger in one place, get a configuration in another place, without passing the Logger reference. Logger's creation can be created after the parent logger can be created after any order, ie, the parent Logger can be created. Log4j will automatically maintain the inheritance tree of Logger.

Appender: Each logger that logs can have one or more appenders, each Appender represents an output destination of a log, such as console or a file. You can add an appender to logger using Logger.AddaPpender (Appender App); you can use Logger.RemoveAppender (Appender App) to remove an Appender for Logger. By default, the Logger's Additive flag is set to True, indicating that the sub-logger will inherit all Appenders of the parent Logger. This option can be reset, indicating that the sub-logger will no longer inherit the Appenders of the father's Logger. Root Logger has a consolerapnder for the target for System.out, so all Loggers will inherit the appender by default. ------ Log4j Apis: Class Logger ------ / / Add or remove an Appender object for the Logger object:. Public void AppAppender (appender app); public void removeappender (appender app); // get And set up the additive logo: Do ​​you inherit your father's respected Appenders:. // Note: When setting the Additive flag to false, you must ensure that the new appender has been set for the logger,:. / / Otherwise log4j will be wrong: log4j: warn no Appenders Could Be Found for logger (xyz).: public boxlean getadditivity (); public void setadditivity; ------ log4j apis: class logger ------ / / For the logger object or Remove an Appender object: PUBLIC VOID AppAppender (Appender App); Public Void RemoveAppender (APPENDER APP); // Get and set the Additive flag: Do you inherit your parent Logger's appenders:. // Note: When setting the Additive flag to false It must be guaranteed to have a new appender for this logger,:. // Otherwise, log4j will be reported: log4j: warn no appenders Could Be Found for logger (xyz).:. Public boolean getadditivity (); public void setadditivity (Boolean Additive );

ConsoleAppender can output the log to the console using the ConsoleAppender object. Each consoleappender has a Target that represents its output destination. It can be system.out, standard output devices (buffer display); or System.err, standard error device (not buffer display). ConsoleAppender How to Use API:. ------ Log4j Apis: Class ConsoleAppender Extends Writerappender ---- // Construction Method, use a Layout object to construct a consolerappender object:. // By default, ConsoleAppender Target is System.out:. Public consoleAppender (Layout Layout); // Construction method, use a Layout object and a Target string constructed the consolerapnder object:. // target's possibly values ​​of consolerapnder.system_out and consolerapnder.system_err: PUBLIC ConsoleAppender (Layout Layout, String Target); ------ Log4j Apis: Class ConsoleAppender Extends Writerappender ------ // Constructor, use a Layout object to construct a ConsoleAppender object:. // By default The Target of ConsoleAppender is System.out:. Public ConsoleAppender (Layout Layout); // Construct Method, use a Layout object and a Target string constructed the consolerapnder object:. // Target may take the value of consolerappender.system_out and consolerapre. System_err:. Public consoleAppender (layout layout, string Target);

FileAppender You can use the FileAppender object to output the log to a specified log file. How to use the following API:. ------ log4j apis: class fileappender extends Writerappender ---- // Constructor, use a Layout object and log file name to construct a FileAppender object:. Public FileAppender layout layout, String filename) throws IOException; public FileAppender (layout layout, String filename, boolean append) throws IOException; ------ Log4j APIs: class FileAppender extends WriterAppender ------ // constructor, using a layout object and construct a log file name FileAppender objects: public FileAppender (layout layout, String filename) throws IOException; public FileAppender (layout layout, String filename, boolean append) throws IOException;.

RollingFileAppender can use the FileAppender subclass ROLLINGFILEAPPENDER object to output the log into a specified log file. Different are the size of the log files, which will scroll upward when the log content exceeds the maximum size (the oldest log is erased). You can also specify how many backups do as log files in this class object. Specific use methods References are as follows:. ------ log4j apis: class rollingfileappender extends FileAppender ------ // Construction method, use a Layout object and log file name to construct a RollingFileAppender object:. 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 file:. public int getMaxBackupIndex (); public void setMaxBackupIndex (int index); // Get and set the maximum size of the scrolling log file:. Public long getMaximumFileSize (); public void setmaximumfilesize (long size); ----- log4j apis: class rollingfileappender extends FileAppender ------ // Construction method Use a Layout object and log file name to construct a RollingFileAppender object:. Public RollingFileAppender (Layout Layout, String FileName) Throws oException; Public RollingFileAppender (Layou t layout, string filename, boolean append "Number of numbers for the log backup file: // Get and set the number of log backup files:. public int getMaxbackupindex (); public void setmaxbackupindex (int index); // Get and set the maximum size of scrolling log files :. Public long getMaximumFileSize (); public void setmaximumfilesize (long size); Layout: The log format is connected to a Layout; the Layout task is to format the user's Logging request, the Appender task is to put the layout format The modified output content is sent to the designated destination.

PatternLayoutPatternLayout is a subclass of Layout to control the log's output format using the format control string used in a C language's Printf function. How to use the following API:. ------ log4j apis: class patternLayout Extends Layout ---- // There is no parameter constructor, use default_conversion_pattern to construct a patternLayout:. // Note: default_conversion_pattern is "% M% n ", only print message information:. public patternLayout (); // Construction method, use custom Pattern to construct a patternLayout:. public patternLayout (String Pattern); // Get and set the log pattern:. Public String getConversionPattern (); public void setConversionPattern (String pattern); ------ Log4j APIs:. class PatternLayout extends Layout ------ // constructor without parameters, a configuration using DEFAULT_CONVERSION_PATTERN PatternLayout: // NOTE: DEFAULT_CONVERSION_PATTERN For "% m% n", only print message information:. Public patternLayout (); // Construction method, use custom Pattern to construct a patternLayout:. Public patternLayout (String Pattern); // Get and set the log of the patternLayout object Pattern:. PUBL IC string getConversionPattern (); public void setconversionpattern (String Pattern); Patterns in patternlayout is endless

Configuration: Configuring the Configuration for the log4j environment is the configuration of the root logger, including which level is set to the root logger; add which appenders, and so on. These can be implicitly completed by setting the method of setting the system properties, or the XXXConfigurator.configure () method can be called in the program to explicitly complete.

The default log4j initialization process Logger class's Static Initialization Block is the default initialization of the log4j environment. Note: If the programmer has configured the log4j environment by setting the system properties, it is not necessary to reverse the XXXConfigurator.configure () method is required to configure the log4j environment. Logger's Static Initial Block will check a series of Log4j defined system properties when the initialization process is completed. What it does is as follows:

Check the system properties log4j.defaultinitOverride, if this property is set to false, perform initialization; otherwise (as long as false, no matter what the value, no value, no value), skip initialization. Assign the value of the system attribute log4j.configuration to the variable resource. If the system variable is not defined, the resource assigns "log4j.properties". Note: It is recommended to use the method for defining the Log4j.configuration system properties in Apache's Log4J documentation to set the default initialization file is a good way. Try to convert the resource variable into a URL object URL. If the general conversion method is not, the org.apache.log4j.helpers.Loader.getResource (Resource, Logger.class) method is called to complete the transformation. If the URL ends with ".html", the method Domconfigurator.configure (URL) is called to complete the initialization; otherwise, the method PropertyConfigurator.configure (URL) is called to complete the initialization. If the resource specified by the URL cannot be obtained, the initialization process is jumped out. BasicConfigurator.configure () BasicConfigurator.configure () method configures the log4j environment using the simplest method. Note: The so-called configuration log4j environment is to configure root logger because all other Loggers are offspring of root logger, so they will inherit the nature of root logger. The task of BasicConfigurator.configure () is:

Create a PatternLayout object with default Pattern P: patternlayout p = new patternLayout ("% - 4R [% t]% - 5P% C% X -% M% N"); Create consOLLAPPENDER object A with p, the target is System.out, standard output device: ConsoleAppender a = new ConsoleAppender (p, ConsoleAppender.SYSTEM_OUT); ConsoleAppender p increases as a root logger: rootLogger.addAppender (p); the log level of the root logger to DEBUG level: rootLogger.setLevel (Level.DEBUG );

XML format log4j profile Overview XML format log4j profile needs to be read using the org.apache.log4j.html.domconfigurator.configure () method. The syntax definition of the XML file can be found in the Log4J release package: org / apache / log4j / xml / log4j.dtd.

The tree structure of the XML configuration file of the log4j of the log4j of the XML configuration file is shown below, and it is noted that the following figure shows only the commonly used portions. :. 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 | LOG4J: Configuration | - Appender Name, Class) | | | - Param (Name, Value) | - Layout (Class) | | | | - Param (Name, Value) - Logger (Name, Additive) | | | - Level (Class, Value) | | | | | - Param (Name, Value) | - Appender- REF - ROOT | - PARAM (Name, Class) - Level | | | - Param (Name, Value) - appender-ref (Ref)

The head of the XML Declaration and DTDXML configuration file includes two parts: XML declarations and DTD declarations. The format of the head is as follows::. log4j: configure (root element)

XMLns: log4j [#fixed attribute]: Defines the namespace of log4j, and obtains the value "http://jakarta.apache.org/log4j/" Appender [* child]: an appender child element defines a log output destination logger [ * Child]: A logger child element defines a log writing Root [? child]: root child element defines root logger

The appenderappender element defines a log output destination.

Name [#Required Attribute]: Define the name of the appender to reference the class [#Required Attribute] later: Defining the full name param [* child] of the class belonging to the Appender object: Create an Appender object to the parameters of the class constructor Layout [? Child]: This appender uses the layout object

The LayoutLayout element defines a log format that connects to an Appender.

Class [#Required Attribute]: Defines the full name param [* child] of the class belonging to the Layout object: Parameters that pass to the class constructor when the Layout object is created.

LoggerLogger elements define a log output.

Name [#Required Attribute]: Defines the name of the Logger so that the additive [#enum attribute] is referenced later: True "or" false ", whether to inherit the parent Logger attribute Level [? child]: Define this logger log level appender-ref [* child]: Defines the output destination of the logger

Rootroot elements define root log outputer root logger.

Param [* child]: Parameters that pass to the class constructor when creating a root logger object: Defines the root logger log level appender-ref [* child]: Define the output destination of root logger

The Levellevel element defines the log level of the Logger object.

Class [#implied attribute]: Defines the class belonging to the Level object. By default, "Org.apache.log4j.L.LEVEL class value [#Required Attribute]: assigns a value for the Level object. Possible value is from small to larger as" all "" Debug "," info "," warn "," error "," fatal ", and" OFF ". When the value is" OFF ", it means that there is no log information is outputted by the output param [* child]: Create a Level object Parameters to the class constructor The Appender-RefaPpender-Ref element references the name of an Appender element to add an Appender for the Logger object.

Ref [#Required Attribute]: Reference Appender-Ref Element No Child Elements

Paramparam elements provide parameters for the constructor of the class when creating an object. It can be sub-elements of an elements such as Appender, Layout, Filter, Errorhandler, Level, CategoryFactory, and root.

Name and value [#Required Attributes]: A group of names that provide parameters to PARAM elements No child elements

Configuring Appender and Layout in an XML file to create different appender objects or different Layout objects to call different constructors. You can use param child elements to set different parameter values.

Creating a consolerappener object consolerappender constructor does not accept other parameters. : ... ... ... ... ... > ... ... ... ... ... ... ... ... ... ... ...

Creating a FileAppender object You can pass two parameters for the FileAppender class: file represents the log file name; append means that if the file already exists, if the log is added to the end of the file, it may take the value "true" and "false" (default) . : ... ... ... ... ... ... ... ... ... ... ... ... ...

Creating a ROLLINGFILEAPPENDER object In addition to file and append, two parameters can be passed for the construction method of the ROLLINGFILEAPPENDER class: the number of MaxBackupIndex backup log files (default is 1); MaxFileSize indicates the maximum number of bytes allowed by log files (default is 10m ). : ... ... ... ... ... ... ... ... ... ... .... ...

Creating a PatternLayout Object You can deliver parameters ConversionPattern. : ... ... ... ... ... ... ... ... ... ... ... ... ...

I use the XML file to configure a simple example of the Log4j environment for the WSOTA project to develop Java Web Start's fat client, using the following XML file configuration log4j environment (file named wsota-rc.log4j.html): :.

========================================================== -> -> -> <> <

! Doctype log4j: Configuration System "Log4j.dtd"> <

! - a console appender -> < Level value = "OFF" /> -> -> Used in the fat client program The code is configured using an external XML file to configure the log4j environment, and note that the code segment is located in the static initialization block of the program's main Class, which contains the following code and XML Set the file 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"));} ... ...} Import Org.Apache.log4j .html.domconfigurator; public class sapframe extends jframe {static {domconfigurator.configure (SAPFrame.Class.GetResource ("wsota-rc.log4j.html));} ... ...} log4j Coding habits

Let each class have a Logger object of Private Static, which is used to output all log information in this class to use an XML file to complete the configuration of the Log4j environment. Place the configuration code of the log4j environment in the static initial block in the project's Main Class. Note: In one project, the log4j environment only needs to be configured once, not in each class that uses the logger, you need to call once with myclass.class as a parameter to create the static logger object supplement to this class ...

Reference

Log4J homepage related documentation: http://jakarta.apache.org/log4j/docs Ashley JS Mills log4j tutorial: http://supportweb.cs.bham.ac.uk/documentation/tutorials/docsystem/build/Tutorials /LOG4J/LOG4J.HTML

转载请注明原文地址:https://www.9cbs.com/read-48526.html

New Post(0)