Java Log Management: log4j, commons-logging, Slf4

Source: Internet
Author: User
Tags getmessage log log syslog

1, log4j
    • Overview

Log4j is an open source project for Apache, mainly used to do the log management work in Java development. It is mainly composed of three important components. You can manage the priority of logs, output destinations, and output formats. Its configuration file mainly has XML and properties two kinds of, of course, can also be configured in the program, but the actual development of the general use of properties file.

    • Components of the log4j
1.1. Priority of log information (level)

There are 7 log levels:off, FATAL, ERROR, WARN, INFO, DEBUG,all, and the level is reduced from one time to the next.

off: Turn off all log records

Fatal: Logs a critical error and causes the application to exit

error: Record a serious error, but will not affect the program's continued operation

Warn: Logging warnings

Info: Information that is more meaningful in the recording program

Debug: Record details in a program

All: Log all logs

1.2, the output destination of log information (Appender)

Log4j can send logs to consoles, files, GUI components, even socket servers, NT Event loggers, UNIX Syslog daemons, and more.

Commonly used in the following categories:

Org.apache.log4j.ConsoleAppender (console)
Org.apache.log4j.FileAppender (file)
Org.apache.log4j.DailyRollingFileAppender (Generate a log file every day)
Org.apache.log4j.RollingFileAppender (creates new files when the file size reaches the specified size)
Org.apache.log4j.WriterAppender (send log information in stream format to any specified location)
Org.apache.log4j.jdbc.JDBCAppender (writes log information to the database)

1.3. Output format of log information (Layout)

There are several main output formats:

Org.apache.log4j.HTMLLayout (HTML table Form)
Org.apache.log4j.PatternLayout (specify format by expression)
Org.apache.log4j.SimpleLayout (simple string containing only the level and information of the log information)
Org.apache.log4j.TTCCLayout (contains information about the time, thread, category, etc.) of the log

Expressions and C are similar in style when using expressions to specify the format, with the following parameters:

%the message specified in the M 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%n outputs a carriage return newline character, the Windows platform is "RN" and the 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 A:Ten: -,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 ( The NDC (nested diagnostic environment) associated with the output and current line threads, especially for multi-client multithreaded applications such as Java Servlets. Percent: Output a "%" character%F: The name of the file where the output log message was generated%L: line number in the output code%m: Output the message specified in the code, resulting in the log specific information%n: Output a carriage return line break, Windows platform is "\ r \ n", Unix platform for "\ n" Output log information wrapping can be in%a modifier is added to the pattern character to control its minimum width, maximum width, and text alignment. such as:1)%20c: Specifies the name of the output category, the minimum width is 20, if the category name is less than 20, the default is the right alignment. 2%-20C: Specifies the name of the output category, the minimum width is 20, if the category name is less than 20, "-"number specifies left-justified. 3)%. 30c: Specify the name of the output category, the maximum width is 30, if the category name is greater than 30, will be the left more than the character of the cut off, but less than 30 will not have a space. 4)% -.30c: If the category name is less than 20, fill in the blanks, and right-aligned, if its name is longer than 30 characters, it is exported from the left hand-sold characters are truncated.
1.4. Configuration file Format (properties)

Log level settings :

Log4j.rootlogger = [level], Appendername, Appendername


Destination of output :

#定义appenderName输出到控制器log4j. Appender.appendername=org.apache.log4j.consoleappender# Define the layout mode for appendername PaternLayoutlog4j.appender.appenderName.layout=org.apache.log4j.PatternLayout

Here the Appendername and the upper log level of the appendername is the same, that is, the output of the destination name, can be arbitrarily taken.

output Format configuration :

# define the output format of the Appendername log4j.appender.appenderName.layout.ConversionPattern=%4p [%t] (%f:%l)-%m%n

Below is a complete configuration profile for reference only:

#定义输出端log4j. Rootcategory=info,a1,a2,a3# define A1 output to controller log4j.appender.A1=org.apache.log4j.consoleappender# defines the A1 layout mode as PaternLayoutlog4j.appender.A1.layout=org.apache.log4j.patternlayout# defines the output format of the A1 Log4j.appender.A1.layout.ConversionPattern=%4p [%t] (%f:%l)-%m%n# definition A2 output to file log4j.appender.A2=org.apache.log4j.dailyrollingfileappender# define A2 output to which file Log4j.appender.A2.File=d:\\log\\syslog.log# defines the maximum length of the A2 output file #log4j.appender.a2.maxfilesize=1kb# defines the number of backup files for A2 #log4j.appender.a2.maxbackupindex=3#定义A2的布局模式为PatternLayoutlog4j. Appender.A2.layout=org.apache.log4j.patternlayout# defines the output mode of the A2 Log4j.appender.A2.layout.ConversionPattern=%D{YYYY-MM-DD hh:mm:ss}:%p%t%c-%m%n# define A3 output to the database log4j.appender.A3=Org.apache.log4j.jdbc.JDBCAppenderlog4j.appender.A3.URL=jdbc:mysql://localhost:3306/db_log4jLog4j.appender.a3.driver=Com.mysql.jdbc.Driverlog4j.appender.A3.user=Rootlog4j.appender.A3.password=root# defines the layout of the A3 and the SQL statements executed Log4j.appender.A3.layout=Org.apache.log4j.PatternLayoutlog4j.appender.A3.layout.ConversionPattern=insert into Tb_log (Createdate,thread,level,class, message) VALUES ('%d','%t','%-5p','%c','%m')

Below is a Java test code:

Import Org.apache.log4j.Logger;

Logger Logger = Logger.getlogger (log4jtest.class);if(logger.isdebugenabled ()) {Logger.debug (NewException ("testlog4j Debug Demo."). GetMessage ());}if(logger.isinfoenabled ()) { (NewException ("testlog4j Info Demo."). GetMessage ());} Logger.error (NewException ("testlog4j error Demo."). GetMessage ()); Logger.fatal (NewException ("testlog4j fatal demo."). GetMessage ());
2, Commons logging
    • Overview

Apache has made a series of log toolkits for different development languages, can be used on Java,. NET, PHP, C + +, and has a consistent style of operation for these logs, where commons-logging (JCL) is implemented, Commons-logging is mainly written for programmers who need to use different log architectures for development in different environments, including Apache log4j and Java log. Use Commons-loogging's log interface and decide which log schema to use at run time. Now using commons-logging and log4j has become a standard solution for Java logs.

You can already use log4j, but why use commons-logging? Here, commons-logging is equivalent to a unified log interface set, of course, he also has implemented Simplelog, but the function is very weak. The implementation of which log is selected at run time (for example, log4j) makes the post-change log framework very convenient and requires only the jar package to be changed. In addition, Commons-logging's log management operations are richer and simpler.

    • Compatibility of commons-logging and log4j

LOG4J does not rely on any project, here points can be found in Log4j's official website:

Commons-logging relies on dependency on dependencies such as compilation dependencies and test dependencies, so here you can find commons-logging and which version of LOG4J compatibility is best (obviously a build-dependent version). Specific dependencies are visible:

Compile dependency: Use the source code to compile the dependency, for example: Get the commons-logging source, want to compile to get commons-logging.jar, then need to provide the dependency of those jar package.

When used in conjunction with commons-logging and log4j, the Java test code is as follows:

Import Org.apache.commons.logging.Log;
Import Org.apache.commons.logging.LogFactory;

Log log = Logfactory.getlog (log4jtest.class);if(log.isdebugenabled ()) {Log.debug (NewException ("log4jcommonslogging Debug Demo."). GetMessage ());}if(log.iserrorenabled ()) {Log.error (NewException ("log4jcommonslogging error Demo."). GetMessage ());}if(log.isinfoenabled ()) { (NewException ("log4jcommonslogging Info Demo."). GetMessage ());}if(log.isfatalenabled ()) {Log.fatal (NewException ("log4jcommonslogging fatal demo."). GetMessage ());}

Java Log Management: log4j, commons-logging, Slf4

Related Article

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: 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.