"Turn" log4j detailed and simple construction

Source: Internet
Author: User
Tags print format

Original link: http://www.cnblogs.com/mailingfeng/archive/2011/07/28/2119937.html

Log4j is a very powerful log recording software.

First of all, of course, get the log4j jar file, we recommend the 1.2.X version:

Http://logging.apache.org/log4j/1.2/download.html

Let's take a look at Log4j's class diagram.

Logger-log writer for programmers to output log information
Appender-Log destination, output formatted log information to the specified place
Consoleappender-Appender of the destination for the console
Fileappender-Destination for files of Appender
Rollingfileappender-Appender of the destination for files of limited size
layout-Log formatter, used to format the programmer's logging request as a string
Patternlayout-Format The layout of the logging request with the specified pattern


Log4j Basic Use Method


LOG4J consists of three important components: the priority of the log information, the output destination of the log information, and the output format of the log information. The priority of log information is high to low with error, WARN, INFO, DEBUG, respectively, to specify the importance of this log information; the output destination of the log information specifies whether the log will be printed to the console or the file, and the output format controls the display of the log information.

First, define the configuration file (the file name is generally used log4j.properties, placed in the SRC directory)

In fact, you can also configure the LOG4J environment in your code without using the configuration file at all. However, using a configuration file will make your application more flexible. LOG4J supports two configuration file formats, one in XML format and one Java attribute file (key = value). Here's how to use the Java attributes file as a configuration file:

1. Configure the root logger, whose syntax is:

Log4j.rootlogger = [level], Appendername, Appendername, ...

Level is the priority of logging, which is divided into off, FATAL, ERROR, WARN, INFO, DEBUG, all, or levels you define. LOG4J recommends using only four levels, with the priority from high to low being error, WARN, INFO, DEBUG. By defining the level here, you can control the switch to the appropriate level of log information in your application. For example, if the info level is defined here, the log information for all debug levels in the application will not be printed. Appendername refers to where the B log information is exported. You can specify multiple output destinations at the same time.

2. Configure the log information output destination Appender, whose syntax is:

Log4j.appender.appenderName = Fully.qualified.name.of.appender.class
Log4j.appender.appenderName.option1 = value1
...
Log4j.appender.appenderName.option = Valuen

Among them, LOG4J provides the following types of Appender:
Org.apache.log4j.ConsoleAppender (console),
Org.apache.log4j.FileAppender (file),
Org.apache.log4j.DailyRollingFileAppender (generates a log file every day),
Org.apache.log4j.RollingFileAppender (creates a new file when the file size reaches the specified size),
Org.apache.log4j.WriterAppender (send log information in stream format to any specified location)

3. Configure the format (layout) of the log information with the following syntax:

Log4j.appender.appenderName.layout = Fully.qualified.name.of.layout.class
Log4j.appender.appenderName.layout.option1 = value1
...
Log4j.appender.appenderName.layout.option = Valuen

Among them, the layout provided by log4j has several types of E:
Org.apache.log4j.HTMLLayout (Layout in HTML table Form),
Org.apache.log4j.PatternLayout (flexibility to specify layout mode),
Org.apache.log4j.SimpleLayout (contains the level of log information and the information string),
Org.apache.log4j.TTCCLayout (contains information about the time, thread, category, etc.) of the log

log4j formats the log information in a print format similar to the printf function in C, with the following printing parameters:%m The message specified in the output code

%p output priority, i.e. Debug,info,warn,error,fatal
%r output the number of milliseconds that the log information is consumed from the application boot to output
%c output belongs to the class, which is usually the full name of the class
%t output The name of the thread that generated the log event

%m the contents of the log;

%n output a carriage return newline character, Windows platform is "RN", UNIX platform is "n"
%d the date or time of the output log time, the default format is ISO8601, can also be specified after the format, such as:%d{yyy MMM dd hh:mm:ss,sss}, output similar: October 18, 2002 22:10:28,921
%l where the output log event occurs, including the class name, the thread that occurred, and the number of rows in the code. Example: Testlog4.main (testlog4.java:10)

%F the name of the file where the output log message was generated
%l line numbers in the output code

Second, use log4j in code (followed by instance code)

1. Get the Recorder

Using log4j, the first step is to get the logger, which will be responsible for controlling the log information. Its syntax is:

public static Logger GetLogger (String name)

The logger is obtained by the specified name and, if necessary, a new logger is created for the name. Name generally takes the names of this class, such as:

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

2. Read the configuration file (when the properties file is named: Log4j.properties and placed under the SRC file, you can omit this step and the system will automatically load the file)
When the logger is obtained, the second step configures the LOG4J environment with the following syntax:
Basicconfigurator.configure (): Automatically and quickly using the default log4j environment.
Propertyconfigurator.configure (String configfilename): Reads a configuration file written using the Java properties file.

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

3. Inserting record information (formatting log information)

When the two necessary steps are completed, you can easily insert a logging statement with different priority levels into any place you want to log, with the following syntax:
Logger.trace (Object message);
Logger.debug (Object message);
Logger.info (Object message);

Logger.warn (Object message);

Logger.error (Object message);

Logger.fatal (Object message);

Instance Code

Example 1. Fileappender configuration of the patternlayout style

The #设置级别和目的地, which is the output to the destination that file points to
Log4j.rootlogger = Debug, File, Debug-out, info-out

#输出到文件
Log4j.appender.file=org.apache.log4j.fileappender
Log4j.appender.file.file=project.log
Log4j.appender.file.layout=org.apache.log4j.patternlayout

Log4j.appender.file.layout.conversionpattern=%d{absolute}%5p%c{1}:%l-%m%n

#按DEBUG日志级别输出到文件
Log4j.appender.debug-out = Org.apache.log4j.RollingFileAppender
Log4j.appender.debug-out.file = Logs/debug.log
Log4j.appender.debug-out.append = True

# # Output Debug levels above the log
Log4j.appender.debug-out.threshold = Debug

# # Output Debug levels above the log
Log4j.appender.debug-out.maxfilesize = 10240KB

# # Maximum number of log file backups
Log4j.appender.debug-out.maxbackupindex = 5
Log4j.appender.debug-out.layout = Org.apache.log4j.PatternLayout
Log4j.appender.debug-out.layout.conversionpattern =%d{yyyy. Mm.dd HH:mm:ss}%c{1}:%l-%m%n


#按INFO log level output to a file
Log4j.appender.info-out = Org.apache.log4j.RollingFileAppender
Log4j.appender.info-out.file = Logs/info.log
Log4j.appender.info-out.append = True
Log4j.appender.info-out.threshold = info
Log4j.appender.info-out.maxfilesize = 10240KB
Log4j.appender.info-out.maxbackupindex = 5
Log4j.appender.info-out.layout = Org.apache.log4j.PatternLayout
Log4j.appender.info-out.layout.conversionpattern =%d{yyyy. Mm.dd HH:mm:ss}%c{1}:%l-%m%n

Example 2. Consoleappender configuration of the simplelayout style

#设置级别和目的地, which is the location pointed to by out
Log4j.rootlogger = Debug, Out

#指向控制台, using Simplelayout
Log4j.appender.out = Org.apache.log4j.ConsoleAppender
Log4j.appender.out.target=system.out

Log4j.appender.out.layout = Org.apache.log4j.SimpleLayout

Example 3. Configuration of the combined Appender (including file and out, name customizable), plus one logger configuration

The #设置级别和目的地, which is output to the destination that file points to (this is set to the info level, indicating that only the priority higher than info is output to the destination. For example, the debug message does not output)

Log4j.rootlogger = info, file, out

#配置convention日志记录logger级别为DEBUG, the log output will end with the Appender set in Rootlogger

Log4j.logger.org.apache.struts2.convention=debug

#配置hibernate的hbm2dll日志记录级别为DEBUG, output to out, which overrides the configuration of the parent Logger--rootlogger

Log4j.logger.org.hibernate.tool.hbm2dll=debug, out

#输出到文件
Log4j.appender.file=org.apache.log4j.fileappender
Log4j.appender.file.file=project.log
Log4j.appender.file.layout=org.apache.log4j.patternlayout
Log4j.appender.file.layout.conversionpattern=%d{absolute}%5p%c{1}:%l-%m%n

#指向控制台, using Simplelayout
Log4j.appender.out = Org.apache.log4j.ConsoleAppender
Log4j.appender.out.target=system.out
Log4j.appender.out.layout = Org.apache.log4j.SimpleLayout

Example 4. Jdbcappender the configuration of the output to the database

Log4j.rootlogger = error, database
#指向JDBC数据库, use Patternlayout
Log4j.appender.database = Org.apache.log4j.jdbc.JDBCAppender
#ERROR或者ERROR以上级别输出
Log4j.appender.database.threshold=error
#配置数据库连接信息
log4j.appender.database.url=jdbc:mysql://localhost:3306/log4j
Log4j.appender.database.driver=com.mysql.jdbc.driver
Log4j.appender.database.user=root
Log4j.appender.database.password=admin
#配置sql语句
Log4j.appender.database.sql=insert into Tb_log (date, priority, message, classname) VALUES ('%d ', '%p ', '%m ', '%c ')
#配置PatternLayout
Log4j.appender.database.layout=org.apache.log4j.patternlayout
Log4j.appender.database.layout.conversionpattern=%-d{yyyy-mm-dd HH:mm:ss:SSS}%m

Example 5. Use log4j in your code.

Package Com.mai.test;import Org.apache.log4j.Logger;
Import Org.apache.log4j.PropertyConfigurator;

public class Log4jtest {

public static void Main (string[] args) {

Logger log = Logger.getlogger (Log4jtest.class);
The path here is relative to the project root, but if log4j.properties is placed in the SRC directory, you can omit this sentence because the file is loaded automatically by the system
Propertyconfigurator.configure ( "Src/log4j.properties" );
Log.debug ("Yes,debug");
Log.info ("Yes,info");
Log.error ("Yes,error");
Log.warn ("Yes,warn");
}

}

output: (Only out-of-console loggers are configured here, using Simplelayout)

Debug-yes,debug

Info-yes,info

Error-yes,error
Warn-yes,warn

"Turn" log4j detailed and simple construction

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.