Java Log Management Method (reprint)

Source: Internet
Author: User
Tags getmessage log log syslog

Original address: http://www.cnblogs.com/leocook/p/log_java.html

The following 4 types of log management schemes are common in Java development:

1. commons-logging + log4j

2. log4j

3. slf4j + log4j + commmons-logging

4. slf4j + log4j

Original address: http://www.cnblogs.com/leocook/p/log_java.html

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:

%M output code specified in the message%P-Output priority, i.e. debug,info,warn,error,fatal%R output the number of milliseconds to output the log information from the application startupC Output belongs to the class, which is usually the full name of the class in%T output the name of the thread that generated the log event%n Outputs a carriage return newline character, the Windows platform is "RN", 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 to: October 18, 200222: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)%x: The NDC (nested diagnostic environment) associated with the output and current line threads, especially for multi-client multithreaded applications like Java Servlets. Percent: Output a "%" character%f: The file name where the output log message was generated%l: Line numbers in the output code%m: Output The message specified in the code, the resulting log specific information%n: output a carriage return newline character, the Windows platform is "\ r \ n", the UNIX platform for "\ n" Output log information line can be%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, "- 3)%.30c: Specifies the name of the output category, the maximum width is 30, If the category name is greater than 30, the left-most character is truncated, but less than 30 will not have a space. 4)%20.30c: If the category name is less than 20, fill in the blanks, and right-align, if its name is longer than 30 characters, Cut off the characters that are exported from the left hand side. 

1.4. Configuration file Format (properties)

Log level settings :

Log4j.rootlogger = [level], Appendername, Appendername

Level:off, FATAL, ERROR, WARN, INFO, DEBUG, all

Destination of output :

#定义appenderName输出到控制器log4j. Appender.appendername=org.apache.log4j.consoleappender# Defines 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# defining 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# defining 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 A3 and the SQL statements that are 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 (log4j):

Import Org.apache.log4j.Logger;

Logger Logger = Logger.getlogger (log4jtest.Class);If(Logger.isdebugenabled ()) {Logger.debug (New Exception ("Testlog4j Debug Demo. "). GetMessage ());} if (logger.isinfoenabled ()) {Logger.info (new Exception (testlog4j info demo. "new Exception ( " testlog4j error demo. "). GetMessage ()); Logger.fatal ( new Exception ( Testlog4j Fatal demo.
/span>

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: http://logging.apache.org/log4j/2.x/dependencies.html.

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: http://commons.apache.org/proper/commons-logging/dependencies.html.

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 combined with commons-logging and log4j, the Java test code is as follows (commons-logging + log4j):

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

Log log = Logfactory.getlog (log4jtest.Class);If(Log.isdebugenabled ()) {Log.debug (New Exception ("Log4jcommonslogging Debug Demo."). GetMessage ());}If (Log.iserrorenabled ()) {Log.error (new Exception ( Log4jcommonslogging Error Demo.  "). GetMessage ());} if (log.isinfoenabled ()) {Log.info (new Exception (log4jcommonslogging info Demo. "if (log.isfatalenabled ()) {log.fatal (new Exception (log4jcommonslogging fatal Demo. "          

3, SLF4J

Similar to Apache commons-logging, but it is statically bound to the log library at compile time, and commons-logging is the mechanism of dynamic lookups, which is the only log library that is actually used when the program runs.

    • The necessity of SLF4J

Commons-logging is a dynamic find mechanism, the program runs to find the real log library, is to use ClassLoader to find, load the log library. However, there is a drawback, such as OSGi development, in order to maintain the independence of plug-ins, plug-ins can only use their own classloader, which makes Apache commons-logging can not work.

    • Advantages of SLF4J

      • More Elegant logging methods

If you use only log4j, you need to determine the current log level each time you log logs, for example:

If(logger.isdebugenabled ()) {    logger.debug (new Exception ("testlog4j Debug Demo.") ). GetMessage ());}     

However, when using SLF4J, you need only the following:

Logger.debug ("Hello world:{}",new Exception ("testlog4jslf4j Debug Demo."). GetMessage ());   

SLF4J the bottom layer will recognize the log bounds, so that you do not have to judge, greatly simplifying the writing.

In addition, placeholder ' {} ' is provided to make the writing layout more flexible.

      • Reduce the memory consumption of the log system

SLF4J is the loading of deferred strings, if the log level is higher than debug in the context of the above code, then new Exception ("Testlog4jslf4j debug Demo."). GetMessage () This piece of content will not be loaded.

In addition, placeholders reduce the concatenation of strings in log messages, reducing memory and CPU performance consumption.

    • log4j + slf4j + commons-logging

in such a structure, the Commons-logging interface is used , slf4j to determine what kind of log implementation is used by the underlying implementation.

Required JAR Packages:

Log4j-1.2.17.jar log4j Implementation Library
Slf4j-api-1.7.7.jar SLF4J Library
Slf4j-log4j12-1.7.7.jar log4j adapter and static bindings log4j the underlying implementation
Jcl-over-slf4j-1.7.7.jar provides the Commons-logging interface, which is implemented by SLF4J to decide which implementation to use

The test code is the same as the code in the code sample combined with commons-logging and log4j (slf4j + log4j + commmons-logging), changing the log frame, etc. without modifying the code, is not very convenient. For compatibility between packages, you can download the SLF4J package and view the Pom file inside the extract.

    • log4j + slf4j

in such a structure, the SLF4J interface is used , and the log library that is used is determined by the log library under compile-time classpath. personally recommend this method.

Required JAR Packages:

Log4j-1.2.17.jar log4j Implementation Library
Slf4j-api-1.7.7.jar SLF4J Library
Slf4j-log4j12-1.7.7.jar log4j adapter and static bindings log4j the underlying implementation

The test code is as follows (slf4j + log4j):

Import Org.slf4j.logger;import org.slf4j.LoggerFactory; Logger Logger = Loggerfactory.getlogger (slf4jtest.class), Logger.debug ("some thing: {}",new Exception ("testlog4jslf4j Debug Demo.") ). GetMessage ()); Logger.error (new Exception ("testlog4jslf4j error demo.") ). GetMessage ()); Logger.info (new Exception ("testlog4jslf4j info demo."). GetMessage ());                  

The above four methods of processing logs in Java, see the following references:

Http://www.importnew.com/7450.html

http://singleant.iteye.com/blog/934593

Original address: http://www.cnblogs.com/leocook/p/log_java.html

Java Log Management Method (reprint)

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