Log4j Concise Manual (1/3)

Source: Internet
Author: User
Log4j Concise Manual

1. Overview
This article describes the unique features of log4j APIs and its design principles. Log4j is an open source project based on many authors. It allows developers to control log output at any interval. It allows you to flexibly set runtime settings by setting an external configuration file. Most importantly, log4j has a stable learning curve. Note: Based on feedback from users, it is very addictive.

2. Introduction

Almost all large applications include their own logs and tracking APIs. Following this rule, the E. U. Semper project decided to write its own tracking Pai. This is the beginning of 1996. After numerous enhancements, several variants, and a lot of work, the API became today's log4j, a popular Java log package. This package is released using the Apache Software License protocol, a mature open source? protocol. The latest log4j version, including all source code, class files and documents, can be found at http://jakarta.apache.org/log4j. By the way, log4j has provided interfaces to C, C ++, C #, Python, Ruby, and Eiffel languages.

It is a low-tech method to insert logs into the code for debugging, but it may be the only method because the debugger is not always available or adaptable, especially for large programs with multi-threaded distribution.

Experience points out that debugging is an important part of the software development cycle.

Log4j has several advantages:

First, it provides an accurate environment for running programs. Once the code is inserted, debugging information can be generated without manual intervention.

Second, log output can be stored in permanent media for future research.

In addition to the development cycle, a fully detailed log package can be used as a statistical tool in the future.

Log4j also has its disadvantages, which may slow down the program. If it is too detailed, it may cause the screen to scroll blindly. To eliminate these situations, log4j is reliable, fast, and scalable. Because logs are rarely the main purpose of an application, designers are trying to simplify the learning and use of log4j APIs.

3. Log category, output source, and Layout

Log4j has three main components: loggers, appenders, and layouts ). These three types of components work together so that developers can record them based on the type and level of information and control the output format and location of the information at runtime.

3.1 log category hierarchy (loggers)

The primary advantage of log4j over the simple use of the system. Out. println () method is its ability to disable some specific information output without compromising the output of other information. This capability is derived from the log namespace, that is, the space declared by all logs, which is classified based on the formula selected by some developers. Previous observations led us to select a category as the central concept of the package. However, since log4j version 1.2, the logger class has been replaced by the catalog class. For those who are familiar with the previous version of log4j, the logger class can be considered only the alias of the category class.

Loggers are specified as entities. Logger names are case-sensitive and follow the naming rules below.

Rules:

2. Name inheritance

If the category name (followed by a vertex) is the prefix of its subcategory name, it is the ancestor of another category.

If a logger and its sub-categories have no other inheritance relationships, we call it the relationship between parent and child.

For example, category "com. foo" is the parent of category "com. Foo. Bar. Similarly, "Java" is the "Java. util" parent, the father of "Java. util. Vector .. This naming rule should be familiar to most developers.

The root category is located at the top of the logger inheritance structure. There are two exceptions:

1. It always exists

2. It cannot be obtained by name.

Call the static method logger. getrootlogger of the class to obtain it. All other logger can obtain their own instances through the static method logger. getlogger. This method takes the desired logger name as the parameter. Some basic logger methods are as follows:

Package org. Apache. log4j;

Public logger class {

// Creation & retrieval methods:

Public static logger getrootlogger ();

Public static logger getlogger (string name );

// Printing methods:

Public void debug (Object message );

Public void Info (Object message );

Public void warn (Object message );

Public void error (Object message );

// Generic printing method:

Public void log (Level L, object message );

}

The level at which loggers can be allocated. A set of all levels includes:

Debug

Info

Warn

Error

Fatal

They are defined in the org. Apache. log4j. level class. Although we do not encourage you, You can inherit the level class to define your own level. Next we will introduce a better method.

If a logger is not assigned a level, it inherits from an ancestor that is assigned a level closest to it.

Formally speaking:

Level 2 Inheritance

For a given logger C, its inheritance level is equal to the level of the first logger with a non-null level from C.

To ensure that all logger can ultimately inherit to a level, the root logger usually has a defined level.

The data in the following four tables demonstrates the results obtained based on the above rules.

Category name
Allocation level
Inheritance level

Root
Proot
Proot

X
None
Proot

X.y
None
Proot

X.y. Z
None
Proot

Example 1

In example 1, only the root logger defines a level. Its level value "proot" is inherited by all other loggers X, x.y, and x.y. Z.

Category name
Allocation level
Inheritance level

Root
Proot
Proot

X
Px
Px

X.y
Pxy
Pxy

X.y. Z
Pxyz
Pxyz

Example 2

In Example 2, all logger instances have an assigned level value, so they do not need level inheritance.

Category name
Allocation level
Inheritance level

Root
Proot
Proot

X
Px
Px

X.y
None
Px

X.y. Z
Pxyz
Pxyz

Example 3

In Example 3, the root logger and X and x.y. Z are allocated with levels of proot, PX, and pxyz respectively. Logger x.y inherits the level px from its parent X.

Category name
Allocation level
Inheritance level

Root
Proot
Proot

X
Px
Px

X.y
None
Px

X.y. Z
None
Px

Example 4

In Example 4, the root logger and X are assigned the levels "proot" and "PX", logger x.y and x.y respectively. Z is inherited from ancestor X, which is assigned a level closest to them.

We need to call one of the instance methods output by logger to implement log requests. The output methods are debug, info, warn, error, fatal, and log.

Define the output method to identify the log request level. For example, if C is a logger instance, it declares that c.info is an info-level log request.

If the request level of a log is higher than or equal to the log level, it can be enabled. Otherwise, it will be disabled. A logger with no scheduling level will be inherited from its parent. This rule is summarized as follows.

2. Basic selection rules

If a log request with a level of P occurs in a logger with a level of Q, if P> = Q, the request is enabled.

This is the core principle of log4j. It assumes that the level is ordered. For the standard level, we define debug <info <warn <error <fatal.

The following is an example of this rule.

// Get a logger instance named "com. foo"

Logger logger = logger. getlogger ("com. foo ");

// Now set its level. Normally you do not need to set

// Level of a logger progamitcally. This is usually done

// In configuration files.

Cat. setlevel (level. info );

Logger barlogger = logger. getlogger ("com. Foo. Bar ");

// This request is enabled, because warn> = info.

Logger. Warn ("low fuel level .");

// This request is disabled, because debug <info.

Logger. debug ("starting search for nearest gas station .");

// The logger instance barlogger, named "com. Foo. Bar ",

// Will inherit its level from the logger named

// "Com. foo" Thus, the following request is enabled

// Because info> = info.

Barlogger.info ("located nearest gas station .");

// This request is disabled, because debug <info.

Barlogger. debug ("exiting Gas Station Search ");

Call the getlogger method to return an instance of a logger object with the same name.

For example,

Categoty x = logger. getlogger ("wombat ");

Categoty y = logger. getlogger ("wombat ");

X and Y refer to the same logger object.

In this way, we can define a logger first, and then we can get the defined logger instance again without passing parameters elsewhere in the code.

Similar to the basic biological theory, the father is opposite to the child. loggers of log4j can create and configure in any order. In particular, a post-instantiated "parent" logger can find and connect its sub-logger.

The log4j configuration environment is usually performed when an application is initialized. The best way is to read a configuration file. We will briefly introduce this method.

Log4j makes it easy to name logger using software components. We can define a logger in each class through the static Initialization Method of logger, so that the logger name is equal to the global name of the class name, And the logger name is implemented. This is an effective and simple way to define a logger. Because the log output contains the name of the log generation class, this naming policy makes it easier for us to locate the source of a log information. Although common, it is one of the common strategies for naming logger. Log4j does not limit the possibility of defining logger. Developers can define logger names as they wish.

However, naming a logger as the location of a class seems to be the best method currently known.

3.2 output source (appenders) and layout (layouts)

The available or disabled log requests are only part of the log4j function. Log4j allows log requests to be output to multiple output sources. In log4j, an output source is called an appender .. Appender includes console, files, Gui components, remote socket servers, JMS ), NT Event loggers (NT Event Logs), and remote UNIX syslog daemons (Remote UNIX background Log Service ). It can also achieve asynchronous record.

A logger can set more than one appender.

Use the addappender method to add an appender to a given logger. For a given logger, every valid log request is forwarded to all appender of the logger and the appender of the parent Logger of the logger. In other words, the appender automatically inherits from its parent. For example, if a root logger has a console appender, all valid log requests will be output to the console at least. If a logger named C has a file-type appender, it will take effect for itself and all its sub-logger. We can also set the additivity flag of appender to false to reload the default appender behavior so that the inherited attributes do not take effect.

The rules for adjusting appender addition are as follows.

Appender additivity)

The output of a log definition named C will continue to itself and its ancestor logger appenders. This is the meaning of the term "appender additivity.

However, if an ancestor logger P of logger C is set to false, the output of C is located to the appender of all c, and appender of all ancestor logger s that start from P.

By default, the additional flag of loggers is true.

The following table is an example.

Logger
Name
Added
Appenders
Additi.pdf
Flag
Output targets
Comment

Root
A1
Not applicable
A1
The root logger is anonymous but can be accessed with the logger. getrootlogger () method. There is no default appender attached to root.

X
A-x1, A-x2
True
A1, A-x1, A-x2
Appenders of "X" and root.

X. y
None
True
A1, A-x1, A-x2
Appenders of "X" and root.

X. y. Z
A-xyz1
True
A1, A-x1, A-x2, A-xyz1
Appenders in "x. y. Z", "X" and root.

Security
A-Sec
False
A-Sec
No appender accumulation since the additi1_flag is set to false.

Security. Access
None
True
A-Sec
Only appenders of "security" because the additianyi flag in "security" is set to false.

Often, you want to customize not only the output source, but also the output format. This is done by attaching a layout to an appender. Layout is responsible for formatting log requests based on your needs. Appender is responsible for sending formatted output to its destination. Patternlayout, as part of the log4j Standard Edition, allows users to specify the log output format in a format similar to the C-language printf method.

For example, patternlayout in the conversion mode of "% R [% T] %-5 p % C-% m % N" will output information similar to the following:

176 [main] info org. Foo. Bar-located nearest gas station.

The first column is the number of milliseconds since the beginning of the program.

The second column is the log thread.

The third column is the log level.

The fourth column is the name of the logger related to the log request. The text after "-" is the expression of information.

Log4j modifies the content of log information based on user-defined formulas. For example, if you often need to record oranges, an object type used in your current project, you can register an orangerenderer, which will be called when an orange needs to be recorded.

Structure Inheritance of similar classes for object rendering. For example, assume that oranges is fruits. If you register a fruitrenderer, all fruits including oranges will be rendered by fruitrenderer. Unless you have registered an orange.

The objectrenderer interface must be implemented for object rendering.

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.