log4j Use Notes

Source: Internet
Author: User
Tags database join db2 html form print format static class

1. log4j's configuration file
LOG4J supports two configuration file formats, one in XML format and one for Java attribute file lg4j.properties (key = value).

1.1. log4j configuration scripts in properties format
The Lg4j.properties file is used as a common configuration file in the following ways:

? Configure Root Logger
Logger is responsible for most of the operations that log records are processed.
Its syntax is:
Log4j.rootlogger = [level], Appendername, Appendername, ...
Where level is the priority of logging, divided into off, FATAL, ERROR, WARN, INFO, DEBUG, all, or custom levels. LOG4J recommends using only four levels, from high to low, respectively, for ERROR, WARN, INFO, and DEBUG. By the level defined here, you can control the switch to log information at the appropriate level in your application. For example, the info level is defined here, and only those that are equal to and above this level are processed, and all DEBUG-level log information in the application is not printed. All: Print all logs, off: Close all log outputs. Appendername is where you specify the output of the log information. Multiple output destinations can be specified at the same time.

? Appender

The configuration log information output destination Appender is responsible for controlling the output of the logging operation.
Its syntax is:
Log4j.appender.appenderName = Fully.qualified.name.of.appender.class
Log4j.appender.appenderName.option1 = value1
Log4j.appender.appenderName.optionN = Valuen

Among them, LOG4J provides the following appender:
Org.apache.log4j.ConsoleAppender (console),
Org.apache.log4j.FileAppender (file),
Org.apache.log4j.DailyRollingFileAppender (a log file is generated every day),
Org.apache.log4j.RollingFileAppender (a new file is generated when the file size reaches a specified size), you can set the file size by log4j.appender.r.maxfilesize=100kb, and you can Log4j.appender.r.maxbackupindex=1 is set to save a backup file.
Org.apache.log4j.WriterAppender (send log information to any specified place in streaming format)
Cases:

Log4j.appender.stdout=org.apache.log4j.consoleappender
Defines an output destination named stdout, Consoleappender for the console.

? Layout

Among them, LOG4J provides the following layout:
Org.apache.log4j.HTMLLayout (layout in HTML form),
Org.apache.log4j.PatternLayout (You can specify layout patterns flexibly),
Org.apache.log4j.SimpleLayout (The level and information string that contains the log information),
Org.apache.log4j.TTCCLayout (contains information about the time, thread, category, and so on that the log was generated)

? Format log Information
LOG4J uses a print format similar to the printf function in C to format the log information, printing parameters as follows:
%M the message specified in the output code
%p output priority, that is, DEBUG, INFO, WARN, ERROR, FATAL
%r output the number of milliseconds it takes to boot to output the log information
The class to which the%c output belongs, usually the full name of the class in which it is located
%t output The name of the thread that generated the log event
%n output a carriage return line feed, Windows platform "RN", Unix platform "n"
%d output log point-in-time date or time, the default format is ISO8601, you can also specify the format after, such as:%d{yyyy MMM dd hh:mm:ss,sss}, Output is similar: October 18, 2002 22:10:28, 921
%l the location where the output log event occurs, including the class name, the thread that occurred, and the number of lines in the code.

Log4j.propertie Sample file:

Log4j.rootcategory=info, Stdout,file

###. Defines the type of output end named stdout
Log4j.appender.stdout=org.apache.log4j.consoleappender
Log4j.appender.stdout.layout=org.apache.log4j.patternlayout
LOG4J.APPENDER.STDOUT.LAYOUT.CONVERSIONPATTERN=[QC]%p [%t]%c.%m (%l) | %m%n

###. The type that defines the output of file name generates a log file for each day.
Log4j.appender.file =org.apache.log4j.dailyrollingfileappender
Log4j.appender.file.file=log.txt
Log4j.appender.file.layout=org.apache.log4j.patternlayout
Log4j.appender.file.layout.conversionpattern=%d-[ts]%p%t%c-%m%n

###. Specifies that all classes under the Com.neusoft package have a level of DEBUG. You can change the Com.neusoft to the name of the package you used for your project.
Log4j.logger.com.neusoft=debug

###. If EHCache is not configured in the project, the following two sentences are configured as ERROR.
Log4j.logger.com.opensymphony.oscache=error
Log4j.logger.net.sf.navigator=error

### Struts Configuration
Log4j.logger.org.apache.commons=error

Log4j.logger.org.apache.struts=warn

### Displaytag Configuration
Log4j.logger.org.displaytag=error

###. Spring Configuration
Log4j.logger.org.springframework=debug

### . Ibatis Configuration
Log4j.logger.com.ibatis.db=warn
### . Hibernate configuration

Log4j.logger.org.hibernate=debug

Log4j.logger.org.apache.velocity=fatal
Log4j.logger.com.canoo.webtest=warn

1.2. log4j configuration scripts in XML format
<?xml version= "1.0" encoding= "GB2312"?>

http://jakarta.apache.org/log4j/">

2. log4j in Java
2.1. commongs-logging+log4j
? Import all required commongs-logging classes:
Import Org.apache.commons.logging.Log;
Import Org.apache.commons.logging.LogFactory;

? Getting loggers

To define a private static class member of a Org.apache.commons.logging.Log class in its own class:
Private Final log = Logfactory.getlog (GetClass ());
The parameters of the Logfactory.getlog () method use class of the current class.

? Output log Information

To output log information using the member method of the Org.apache.commons.logging.Log class:

if (log.isdebugenabled ()) {

Log.debug ("Debug ...");

}
if (log.isinfoenabled ()) {
Log.info ("info ...");
}
if (log.iswarnenabled ()) {
Log.warn ("Warn ...");
}
if (log.iserrorenabled ()) {
Log.error ("error ...");

}
if (log.isfatalenabled ()) {
Log.fatal ("Fatal ...")
}

2.2. Use of log4j alone
? Getting loggers

The logger uses log4j, which is responsible for controlling log information. Its syntax is:

public static Logger GetLogger (String name)

Gets the logger by the specified name and, if necessary, creates a new logger for that name. Name generally takes the names of this class, such as:

static Logger Logger = Logger.getlogger (Test.class.getName ())

? Reading configuration Files

When the logger is obtained, the second step configures the LOG4J environment with the following syntax:

Basicconfigurator.configure (): Automatically and quickly uses the default log4j environment.

Propertyconfigurator.configure (String configfilename): Reads a configuration file written using a Java-specific attribute file.

Example: Propertyconfigurator.configure (".//src//log4j.properties"), if the log4j.properties placed in the engineering root directory can not write this sentence, the program will automatically find the configuration file.

Domconfigurator.configure (String filename): Reads a configuration file in XML form.

? Output log Information

When the two necessary steps are completed, you can easily insert the different priority logging statements into any place you want to log, with the following syntax:

Logger.debug (Object message);

Logger.info (Object message);

Logger.warn (Object message);

Logger.error (Object message);

LOG4J Sample Program

The following is a simple example program to further illustrate how log4j is used. The program code is as follows:

Import org.apache.log4j.*;

Import Org.apache.log4j.PropertyConfigurator;
Import Org.apache.log4j.xml.DOMConfigurator;

public class Logtest {

static Logger Logger = Logger.getlogger (LogTest.class.getName ());

public static void Main (string[] args) {

Propertyconfigurator.configure (".//src/log4j.properties");

Domconfigurator.configure (".//src/log4j.xml");//load. xml file
Logger.debug ("Debug ...");

Logger.info ("info ...");

Logger.warn ("Warn ...");

Logger.error ("error ...");

}

}

3. log4j in Database
3.1. Database configuration
? Import the required drive pack

You need to import the driver package into the service regardless of which database you are using.

? Create the table that you want

First, make sure that you have a log table in your database and maintain the length of the orthography, otherwise the operation will fail when you write to the log

Data Dictionary Description:

CREATE TABLE LOG (

ID INTEGER not NULL PRIMARY KEY,

Logdate DATE,

LogTime time,

Logthread VARCHAR (50),

LogLevel VARCHAR (50),

Logclass VARCHAR (50),

Loglogger VARCHAR (200),

LogMessage VARCHAR (2000)

)

Go

3.2. log4j configuration file
# # Configuration Database Join

Log4j.appender.database=org.apache.log4j.jdbc.jdbcappender

Log4j.appender.database.url=jdbc:db2://127.0.0.1:50000/pbdb

Log4j.appender.database.driver=com.ibm.db2.jcc.db2driver

log4j.appender.database.user=erpt1104

log4j.appender.database.password=erpt1104

Log4j.appender.DATABASE.sql = INSERT into log (logdate,logtime,logthread,loglevel,logclass,loglogger,logmessage) VALUES ('%d{yyyy-mm-dd} ', '%d{hh:mm:ss} ', '%t ', '%p ', '%c ', '%l ', '%m ')

Log4j.appender.database.layout=org.apache.log4j.patternlayout Log4j.appender.DATABASE.layout.ConversionPattern = %D{YYYY MM DD hh:mm:ss,sss}%-5p%t%c%m

Description

%d output log point-in-time date or time, the default format is ISO8601, you can specify the format after, such as:%d{yyyy-mm-dd HH:mm:ss}, output similar: 2007-3-29 17:49:27, just fit to insert SQL Server;

%t the name of the thread that generated the log event;

%p log log_level, such as DEBUG, WARN, or INFO;

The class of the output of%c, usually the full name of the class in which it is located, such as "Inotes.default";

%m the contents of the log;

%l the location where the output log event occurs, including the class name, the thread that occurred, and the number of lines in the code. such as Test.main (TEST.JAVA:33);

%n output a carriage return line break, the Windows platform is "/r/n", and the Unix platform is "/n"

Called in 3.3. Java
Import sun.jdbc.odbc.*;

Import java.sql.*;

Import Org.apache.log4j.Category;

Import Org.apache.log4j.Level;

Import Org.apache.log4j.Logger;

Import Org.apache.log4j.PropertyConfigurator;

Import org.apache.log4j.jdbc.*;

static Logger Logger = Logger.getlogger (Test.class.getName ());

Propertyconfigurator.configure ("Log.properties");

Logger.info ("test");

Run the project, you will see the execution of the SQL statements, the database will be inserted into the relevant data, such as the need to analyze the log, this is not log4j things.

4. Final Note:
The above information is I learn to collate the proceeds, all errors please leave a message

DOC documents can be downloaded from their Web site:

Http://logging.apache.org/log4j/docs/api/index.html

Http://logging.apache.org/log4j/docs/documentation.html

There is another the complete log4j manual (in PDF format) The English version needs to charge, I did not find from the Internet, Spanish translation I do not know, hehe

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.