Commons-logging and log4j log management

Source: Internet
Author: User

Apache log4j Study Notes:Http://www.cnblogs.com/TopZhujia/archive/2010/05/15/1789993.html

(Xml configuration file)

 

Below, the configuration file is Properties

 

Commons-logging + log4j Getting Started Guide [ZT] Original: Zhuang Xiaoli (liigo)
Www.liigo.com
2005-8-13

Why do I use both commons-logging and log4j? Why not only use one of them?
The purpose of commons-Loggin is to provide a unified interface for "All Java log implementations". Its own log functions are usually weak (only one simple simplelog ?), Therefore, it is generally not used independently.

Log4j features are comprehensive and powerful, and is the first choice. I found that almost all Java open-source projects use log4j, but I also found that all projects that use log4j usually use commons-Loggin at the same time. I don't think you want your project to be too closely bound to log4j. Another reason I can think of "using commons-logging and log4j at the same time" is to simplify usage and configuration.

Note that "using commons-logging and log4j at the same time" does not bring more learning, configuration, and maintenance costs than "using log4j separately, it simplifies our work. I think this is one of the reasons why "commons-Loggin is also used for all projects that use log4j.
Commons-what can logging do for us?
1) provides a unified log interface, which is easy to operate and avoids close a coupling between a project and a log implementation system.
2) It is very considerate to help us automatically select the appropriate log Implementation System (this is very good !)
3) it does not even need to be configured

Here, let's take a look at how it "very considerate" helps us to automatically select the appropriate "log implementation system ":

1) First find your own configuration file commons-logging.properties under classpath, if found, use the defined log implementation class;

2) If the commons-logging.properties file is not found, you can use the defined log implementation class to find the system environment variable org. Apache. commons. Logging. log that has been defined;

3) Otherwise, check whether the classpath contains a log4j package. If any package is found, log4j is automatically used as the log implementation class;

4) Otherwise, use the JDK's own log implementation class (the log implementation class is available only after jdk1.4 );

5) Otherwise, use commons-logging to provide a simple log implementation class simplelog;

(The above sequence is not guaranteed to be completely accurate. Please refer to the official documentation)

It can be seen that commons-logging can always find a log implementation class and find the "most appropriate" log implementation class as much as possible. I said it is "very considerate" because: 1. You do not need a configuration file; 2. You can automatically determine whether a log4j package exists. If yes, you can use it automatically; 3. In the most pessimistic case, it is always possible to provide a log implementation (simplelog ).

As you can see, commons-logging is very friendly to programmers and log4j.

To simplify the configuration of commons-logging, do not use the commons-logging configuration file or set system environment variables related to commons-logging, instead, you only need to place the jar package of log4j in classpash. This completes the integration of commons-logging and log4j. What if I don't want to use log4j? You only need to delete the jar package of log4j in classpath.

How should I write the code?
We do the following in the "every person" class that needs to output log information:

1. Import all required commongs-logging classes:
Import org. Apache. commons. Logging. log;
Import org. Apache. commons. Logging. logfactory;
If you want to simplify it, you can combine the two rows into one line:

Import org. Apache. commons. Logging .*;

2. Define a private static member of the org. Apache. commons. Logging. Log class in your class:

Private Static log = logfactory. getlog (youclassname. Class );

Note that static members are defined here to avoid multiple instances.

The parameters of the logfactory. getlog () method use the class of the current class. This is the best method that is generally considered. Why not write logfactory. getlog (this. getclass ())? Because static Class Members cannot access this pointer!

3. Use the org. Apache. commons. Logging. Log class member method to output log information:
Log. debug ("111 ");
Log.info ("222 ");
Log. Warn ("333 ");
Log. Error ("444 ");
Log. Fatal ("555 ");

The log here is the class member variable defined in the second step above. Its type is Org. apache. commons. logging. log, through the member method of this class, we can output log information of different types to the destination (where is the destination? Depending on the configuration, it may be stdout, a file, an email, or even a text message to your mobile phone ...... For details, see log4j. properties below ):
1) debug () Outputs "debug"-level log information;
2) Info () Outputs "information"-level log information;
3) warn () Outputs warning-level log information;
4) error () Outputs "error"-level log information;
5) Output "Fatal error" log information by fatal;

Based on different properties, log information is usually divided into different levels, from low to high: "debug", "info", and "warning (warn) "" error "" Fatal )". Why do we divide the log information into different levels? This is actually convenient for us to better control it. For example, through the log4j configuration file, we can set "output 'debug' and above-level log information" (that is, "debug", "information", "warning", "error", and "Fatal error "), this may be useful to project developers. We can also set "output" warning "and above-level log information" (that is, "warning", "error", and "Fatal error "), this may be useful to end users of the project.

Simply literally, we can draw a general conclusion that the most common ones are debug () and Info (), while warn (), error (), and fatal () it is used only when an event occurs.

From the preceding three steps, we can see that the log interface using commons-logging is very simple and does not need to remember many things: only two types of log, logfactory, in addition, there are very few methods of the two classes (the latter only uses one method, and the former often uses only a few of the methods listed in the third step), and the parameters are very simple.

The method described above is currently used by common applications. It can be said that it is a standardized method, which is used by almost all people. If you do not believe it or want to confirm it, download the source code of several well-known Java open-source projects.

The following provides a complete Java class code:
Java code

Package liigo. testlog; </P> <p> Import Org. apache. commons. logging. log; <br/> Import Org. apache. commons. logging. logfactory; </P> <p> public class testlog {<br/> Private Static log = logfactory. getlog (testlog. class); </P> <p> Public void test () {<br/> log. debug ("111"); <br/> log.info ("222"); <br/> log. waren ("333"); <br/> log. error ("444"); <br/> log. fat Al ("555"); <br/>}</P> <p> Public static void main (string [] ARGs) {<br/> testlog = new testlog (); </P> <p> testlog. test (); </P> <p >}</P> <p> package liigo. testlog; import Org. apache. commons. logging. log; import Org. apache. commons. logging. logfactory; </P> <p> public class testlog {<br/> Private Static log = logfactory. getlog (testlog. class); <br/> Public void test () {<br/> log. debug ("111"); <br/> log.info ("222"); <br/> log. waren ("333"); <br/> log. error ("444"); <br/> log. fat Al ("555"); <br/>}</P> <p> Public static void main (string [] ARGs) {<br/> testlog = new testlog (); testlog. test (); <br/>}< br/>

As long as you ensure that the jar package of commons-logging is in classpath, the above Code can be compiled smoothly. What is the execution result? I'm afraid there will be a big difference. Please continue.

Where is log4j? Does it play a role?
It should be noted that the source code we provided above does not involve log4j at all-this is exactly what we want, and this is one of the goals of commons-logging.

But how can we make log4j play its role? The answer is simple. You only need to meet the requirement that "jar packages with log4j in classpath ". As mentioned above, commons-logging will automatically discover and apply log4j. So as long as it exists, it plays a role. (Does it exist? Naturally, it does not work. commons-logging will select other log implementation classes .)

Note: The configuration file log4j. properties is required for log4j. If the configuration file does not exist in the classpath, or the configuration is incorrect, a running exception is thrown.

In this way, to correctly apply log4j to output log information, the role of log4j. properties is very important. Fortunately, this file has a general template and can be used by copying a copy (slightly modified. Almost every Java project directory contains a log4j. properties file. You can download the source code of several open-source Java projects. At the end of this article, we also attached a template-type log4j. properties file, which can be directly copied and used, or modified as needed. The log4j. properties file will be introduced later.

Here, by the way, we will be prompted: If you don't need to use commons-logging and use log4j separately, the operation will be a little more troublesome, because log4j requires a little more initialization code (compared to commons-logging ):

Java code
Import Org. apache. log4j. logger; <br/> Import Org. apache. log4j. propertyconfigurator; </P> <p> public class testlog4j {</P> <p> static logger = logger. getlogger (testlog4j. class); // first step </P> <p> Public static void main (string ARGs []) {</P> <p> propertyconfigurator. configure ("log4j. properties "); // Second Step <br/> logger. debug ("here is some debug"); // third step <br/> logger.info ("here is some info"); <br/> logger. warn ("here is some warn"); <br/> logger. error ("here is some error"); <br/> logger. fatal ("here is some fatal"); <br/>}</P> <p> Import Org. apache. log4j. logger; import Org. apache. log4j. propertyconfigurator; <br/> public class testlog4j {<br/> static logger = logger. getlogger (testlog4j. class); <br/> // first step <br/> Public static void main (string ARGs []) {<br/> propertyconfigurator. configure ("log4j. properties "); <br/> // Second Step <br/> logger. debug ("here is some debug"); <br/> // third step <br/> logger.info ("here is some info"); <br/> logger. warn ("here is some warn"); <br/> logger. error ("here is some error"); <br/> logger. fatal ("here is some fatal"); <br/>}< br/>

But there will be one more row. However, this at least indicates that referencing commons-logging does not complicate the problem, but is simpler. Here, 1 + 1 is less than 2. This also verifies the previous conclusion.

Summary
Place the jar packages of commons-logging and log4j under classpath and put the configuration files of log4j in classpath.

Using log4j with commons-logging as the log system is a very popular mode in the Java field and is widely used. The combination of the two results: simple + powerful.

Commons-logging provides simple and unified interfaces without additional configuration;

Log4j features are comprehensive and powerful;

Commons-logging only packs log4j (including other log implementations of course) layer by layer, and the specific log output is forwarded internally to log4j behind it for processing; although log4j has done everything, it has never shown itself as a green leaf.

The two are out of the box.

Introduction to log4j. Properties
The following describes the content of the log4j. properties file. The log4j. properties file will be attached as an example:

Except for comments starting with # And empty rows, the first line has the following useful content:

Log4j. rootlogger = debug, console, A1

Log4j. rootlogger is the most important attribute. It defines the "output level" and "output destination" of log information ".

The key is the value after "=", "debug, console, A1". Here we want to divide it into two parts: the first part is before the first comma, and the "output level" is specified "; the second part is followed by "output destination ". Multiple "output destinations" can be specified at the same time, separated by commas.

Specific to the above line: it specifies the "output level" as "debug"; it specifies the "output destination" as "console" and "A1 ".

Note:
1) The "output level" has five optional values: Debug, info, warn, error, and fatal, which are defined by the log4j system.
2) The "output destination" is defined by ourselves, just in log4j. properties. The "output destination" defined in this file includes console, file, rolling_file, socket, lf5_appender, mail, database, A1, and Im. This file can be used as a template because it fully defines a variety of common output destinations (console, file, email, database, etc ).

The following describes the line "log4j. rootlogger = debug, console, A1" in detail:
1) Specify the "output level" as "debug", that is, only the log information with the output level greater than or equal to "debug. If "Warn" is specified here, only the log information output by calling the warn (), error (), and fatal () methods is output to the "output destination ", the log information output by calling the debug () and Info () methods is not output to the "output destination ". Do you understand? Log4j filters and controls the output of log information in this way, which is also the purpose of classifying log information.
2) Specify the "output destination" as "console" and "A1", that is, filter the specified log information based on the log level) both the "console" and "samplemessages. log4j File ".

Why does "console" mean to output log information to "console? Let's take a look at the definition in the following article:

# Apply to the console
Log4j. appender. Console = org. Apache. log4j. leleappender
Log4j. appender. Threshold = debug
Log4j. appender. Console. Target = system. Out
Log4j. appender. Console. layout = org. Apache. log4j. patternlayout
Log4j. appender. Console. layout. conversionpattern = [framework] % d-% C-%-4r [% T] %-5 p % C % x-% m % N
# Log4j. appender. console. layout. conversionpattern = [start] % d {date} [date] % N % P [Priority] % N % x [NDC] % N % T [thread] n % C [category] % N % m [Message] % N

Why does "A1" mean to output log information to "samplemessages. log4j file? You can also refer to the following definition:
Log4j. appender. A1 = org. Apache. log4j. dailyrollingfileappender
Log4j. appender. a1.file = samplemessages. log4j
Log4j. appender. a1.datepattern = yyyymmdd-hh '. log4j'
Log4j. appender. a1.layout = org. Apache. log4j. xml. xmllayout

Note: The definition here does not specify the path of the output file. Its path is actually the value of Java. User. Path.
You should have noticed that when defining the "output destination", you can also specify the log format, time, layout, and other information. Skipped.

Now, I can modify this line as needed:
Log4j. rootlogger = error, console, file, mail

Log information at the "error" and "Fatal" levels is output to the console and files, and an email is sent to the system administrator. Is it nice? (If you mail the "debug"-level log information to the Administrator, I am afraid it will sooner or later blow up his/her mailbox, even if it is using Gmail! I understood the intention of "dividing log information into different levels" again, right ?)

Appendix: a useful log4j. properties file template
# The simple configuration of log4j makes it more and more applications

# The log4j configuration file provides a full set of functions such as output to the console, files, rollback files, sending log emails, output to database log tables, and custom tags. It is enough to choose one or two of them.

# The content of this file (log4j. properties) comes from the network and is not original to liigo.
Log4j. rootlogger = debug, console, A1
Log4j.addivity.org. Apache = true

# Apply to the console
Log4j. appender. Console = org. Apache. log4j. leleappender
Log4j. appender. Threshold = debug
Log4j. appender. Console. Target = system. Out
Log4j. appender. Console. layout = org. Apache. log4j. patternlayout
Log4j. appender. Console. layout. conversionpattern = [framework] % d-% C-%-4r [% T] %-5 p % C % x-% m % N

# Log4j. appender. console. layout. conversionpattern = [start] % d {date} [date] % N % P [Priority] % N % x [NDC] % N % T [thread] n % C [category] % N % m [Message] % N

# Apply to files
Log4j. appender. File = org. Apache. log4j. fileappender
Log4j. appender. file. File = file. Log
Log4j. appender. file. append = false
Log4j. appender. file. layout = org. Apache. log4j. patternlayout
Log4j. appender. file. layout. conversionpattern = [framework] % d-% C-%-4r [% T] %-5 p % C % x-% m % N
# Use this layout for logfactor 5 Analysis

# Apply to file rollback
Log4j. appender. rolling_file = org. Apache. log4j. rollingfileappender
Log4j. appender. rolling_file.threshold = Error
Log4j. appender. rolling_file.file = rolling. Log
Log4j. appender. rolling_file.append = true
Log4j. appender. rolling_file.maxfilesize = 10kb
Log4j. appender. rolling_file.maxbackupindex = 1
Log4j. appender. rolling_file.layout = org. Apache. log4j. patternlayout
Log4j. appender. rolling_file.layout.conversionpattern = [framework] % d-% C-%-4r [% T] %-5 p % C % x-% m % N

# Apply to socket
Log4j. appender. Socket = org. Apache. log4j. rollingfileappender
Log4j. appender. Socket. remotehost = localhost
Log4j. appender. Socket. Port = 5001
Log4j. appender. Socket. locationinfo = true

# Set up for log facter 5
Log4j. appender. Socket. layout = org. Apache. log4j. patternlayout
Log4j. appender. socet. layout. conversionpattern = [start] % d {date} [date] % N % P [Priority] % N % x [NDC] % N % T [thread] % N % C [Category] % N % m [Message] % N

# Log Factor 5 appender
Log4j. appender. lf5_appender = org. Apache. log4j. lf5.lf5appender
Log4j. appender. lf5_appender.maxnumberofrecords = 2000

# Send Logs to emails
Log4j. appender. Mail = org.apache.log4j.net. smtpappender
Log4j. appender. Mail. Threshold = fatal
Log4j. appender. Mail. buffersize = 10
Log4j. appender. Mail. From = web@www.wuset.com
Log4j. appender. Mail. smtphost = www.wusetu.com
Log4j. appender. Mail. Subject = log4j message
Log4j. appender. Mail. To = web@www.wusetu.com
Log4j. appender. Mail. layout = org. Apache. log4j. patternlayout
Log4j. appender. Mail. layout. conversionpattern = [framework] % d-% C-%-4r [% T] %-5 p % C % x-% m % N

# For Databases
Log4j. appender. Database = org. Apache. log4j. JDBC. jdbcappender
Log4j. appender. database. url = JDBC: mysql: // localhost: 3306/test
Log4j. appender. database. Driver = com. MySQL. JDBC. Driver
Log4j. appender. database. User = root
Log4j. appender. database. Password =
Log4j. appender. database. SQL = insert into log4j (Message) values ('[framework] % d-% C-%-4r [% T] %-5 p % C % x-% m % n ')
Log4j. appender. database. layout = org. Apache. log4j. patternlayout
Log4j. appender. database. layout. conversionpattern = [framework] % d-% C-%-4r [% T] %-5 p % C % x-% m % N
Log4j. appender. A1 = org. Apache. log4j. dailyrollingfileappender
Log4j. appender. a1.file = samplemessages. log4j
Log4j. appender. a1.datepattern = yyyymmdd-hh '. log4j'
Log4j. appender. a1.layout = org. Apache. log4j. xml. xmllayout

# Custom appender
Log4j. appender. Im = net. cybercorlin. util. Logger. appender. imappender
Log4j. appender. Im. Host = mail.cybercorlin.net
Log4j. appender. Im. Username = Username
Log4j. appender. Im. Password = Password
Log4j. appender. Im. Recipient = corlin@cybercorlin.net
Log4j. appender. Im. layout = org. Apache. log4j. patternlayout
Log4j. appender. Im. layout. conversionpattern = [framework] % d-% C-%-4r [% T] %-5 p % C % x-% m % N
# End

References
Http://jakarta.apache.org/commons/logging/
Http://logging.apache.org/log4j/docs/

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.