Java Log Framework Introduction __java

Source: Internet
Author: User
Tags log log system log throw exception log4j
Overview

In the first contact with the log frame, by a lot of log frame dizzy, the following will be the overall introduction of the current popular open source log framework, and focus on the log4j log output principle and configuration guidance

Log frame Brief introduction Reference
April JDK's own log frame (java.util.logging), with less efficiency and flexibility, is currently in use http://docs.oracle.com/javase/1.5.0/docs/guide/logging/overview.html#1.0
Jcl Apache Common-logging is the Apache Open Source Log interface system, in the Java system, there are a variety of log implementation, the framework provides only log output interface, in the actual operation, according to the application needs, flexible switch log implementation; Before the SLF4J log interface, there are more jcl+log4j implementation log items; But the framework has a fatal problem: A framework like OSGi does not work properly Http://commons.apache.org/proper/commons-logging/index.html
Slf4j It is also a log interface system, similar to JCL, but it can be run perfectly in a framework such as OSGi compared to JCL, a framework author that implements the Log4j/logback http://www.slf4j.org/
Log4j Using the most extensive log frame system, through the control of the configuration file, we can easily in a specific format, the log output to the console, file, remote log server, supporting the automatic file switching backup Http://logging.apache.org/log4j/1.2/
Logback The framework is the same person as the log4j framework author, because it adjusts the implementation framework, output log performance is higher than log4j, and it supports automatic backup compression, the framework authors strongly recommend the use of Logback replacement log4j http://logback.qos.ch/

Summarized from the table above, we can see that, such as follow-up to new projects, the proposed adoption of SLF4J+LOGBACK implementation, but for many reasons, the current log4j use is still more common, the following will focus on log4j log4j log Output principle

log4j (log for Java) completes the log output mainly through three classes: loggers, Appenders and Layouts

Loggers: A parent-child relationship exists between the instance 1 "logger" for the output log, and the default child logger the corresponding log output request is also printed to all parent logger

For example, there are two classes: COM.UCWEB.ACCOUNT.SDK.TESTA,COM.UCWEB.ACCOUNT.TESTB, and the corresponding log4j.logger.com.ucweb.account.sdk/is configured in the configuration file
the Log4j.logger.com.ucweb.account class Testa corresponds to obtain the corresponding Loggera by Org.apache.log4j.Logger.getLogger (class Clazz);
TESTB corresponds to obtain the corresponding Loggerb through Org.apache.log4j.Logger.getLogger (Class clazz),
then Loggera is Logger, the parent loggerb, and the root logger of Loggera and Loggerb is Rootlogger.
2 "You can use the custom logger name and then GetLogger (String name) to obtain the corresponding instance 3" unique Rootlogger, each application should be configured with a Rootlooger, which is the root of all other logger, If the corresponding logger is not configured, its logs are all printed by default to Rootlogger

Appenders: target for user-defined final log output: console, file, remote server

Most commonly used: Org.apache.log4j.consoleappender/org.apache.log4j.rollingfileappender

Layouts: Define log Output format: Timestamp, thread name, log level, log content, corresponding class to output the log, method to output the log, line number, and MDC information

Most commonly used: Org.apache.log4j.PatternLayout

The relationship between the three:


Each logger can be configured with multiple appender, each appender corresponding to a layout, in the output log, in turn, the log content according to the layout format output corresponding Appender
current usage in the JWS frameworkJWS is evolved from the Playframework framework, Playframework 1.x version is used: slf4j+log4j 2.x version switch to Slf4j+logback JWS the external provided log interface JWs. Logger, it mainly provides two kinds of output interface mode:
Debug/info/warn/error/fatal: This type of interface log defaults to the unified output to the Jws.log log file
 event: This type of interface log defaults to output to the logger name specified by event, such as event ("Error", " MSG Info "), the output value is error.log;

"Disadvantages":

1 The use of non-event mode output log, all logs are output to Jws.log, in multiple threads output log at the same time, there is a resource competition,
 2 use event method although can solve the problem 1, but this way cannot output corresponding log output class and method information;
 3 The current JWS framework, the default provided by the log output layout is not printed "thread name + class Information + method information + Log error line information", very unfavorable positioning problem;
log4j Configuration

Configuration: log4j can be configured by properties/xml two ways (only the file format is different), it is recommended to use the properties file to write the corresponding configuration items, the following gives a log configuration example:

#对一个应用来说, there must be a Rootlooger #所有的Logger配置对应的value值都是类似: level, appender-1[,appender-2,..., appender-n]; #其中级别取值: All,debug , Info,warn,error,fatal,off, recommended: Info,warn,error These three levels #其中Appender-X must be a appender that exists with the current configuration file Log4j.rootlogger=warn , Rootappender   #对应的Appender类别 Log4j.appender.rootappender=org.apache.log4j.rollingfileappender # such as the following attributes are related to the specific Appender category #日志文件路径, relative to the current program running directory Log4j.appender.rootappender.file=logs/root.log #单个日志文件大小-Maximum, The following configuration indicates that Root.log.1 is automatically backed up after the Root.log file size exceeds 20M, and then the new file LOG4J.APPENDER.ROOTAPPENDER.MAXFILESIZE=20MB is overwritten #备份文件最大个如
The following configuration says: After the backup file reaches 100, automatically clears the oldest file log4j.appender.rootappender.maxbackupindex=100 #Layout类别 Log4j.appender.rootappender.layout=org.apache.log4j.patternlayout #下面的配置属性, related to the specific layout category #%d{yyyy-mm-dd HH:mm: SsS} output time information in the corresponding format; #%p log level #[%t] The corresponding thread name #%m corresponding log content #%c the class #%l corresponding output of the log, corresponding to the line number of the class corresponding to the output of the log Log4j.appender.rootAppender.lay Out.
Conversionpattern=%d{yyyy-mm-dd hh:mm:sss} %-5p [%t] %m (%.30c.%l)%n   #自定义logger LOG4J.LOGGER.COM.UCWEB.PROFILE=WARN,PERFMT #Print only the log to the current file switch, not recursively print to the parent logger #这个开关默认是开启 (recursive log to the parent logger), strongly recommend that the business close this switch; log4j.additivity.com.ucweb.profile=false Rolling files Log4j.appender.perfmt=org.apache.log4j.rollingfileappender log4j.appender.perfmt.file=logs/ Monitor.log LOG4J.APPENDER.PERFMT.MAXFILESIZE=20MB log4j.appender.perfmt.maxbackupindex=100 #如配置了Threshold这个属性项, It indicates that the Appender output log, the corresponding level threshold, #log4j先校验logger对应的日志级别, and then use the threshold corresponding log level, in order to prevent configuration errors, recommend a special case, do not configure the property item # Log4j.appender.perfmt.threshold=info #这个配置项表示是否立即刷新日志内容到磁盘, default is turned on, the default value #log4j is recommended. appender.perfmt.immediateflush= True Log4j.appender.perfmt.layout=org.apache.log4j.patternlayout log4j.appender.perfmt.layout.conversionpattern= %d{yyyy-mm-dd hh:mm:sss} %-5p [%t] %m (%.30c.%l)%n   #控制台 log4j.appender.console=
Org.apache.log4j.ConsoleAppender Log4j.appender.console.layout=org.apache.log4j.patternlayout LOG4J.APPENDER.CONSOLE.LAYOUT.CONVERSIONPATTERN=[%D{YYYY-MM-DD hh:mm:ss}] %p ~ %m%n

Load mode: Boot phase loading:

By adding system environment variables: log4j.configuration= point to the URL of the corresponding log4j configuration file
Load during run:
1 The program launches the entrance, through Propertyconfigurator.configure (), dynamically loads the log4j configuration file,
2) log4j itself supports the periodic check configuration file whether modifies, if the modification will automatically reload;
3 code through the log4j provided by the API, modify the corresponding log level

Note: 1 each independent business (or subsystem) should be independent of a logger, each logger write the log file independently, so that their respective business log independent, that is, to facilitate the problem positioning, improve the efficiency of the log processing

For simplicity, the code design phase is distinguished by the package name, such as the following business:
forum: Com.ucweb.bbs:   com.ucweb.ka  Portal: com.ucweb.game;
So when you set up logger, By using the following configuration, all classes under this package are only entered into their business log files by default:
#BBS日志 Log4j.logger.com.ucweb.bbs=warn,bbsappender Log4j.additivity.com.ucweb.bbs=false
Log4j.appender.bbsappender=org.apache.log4j.rollingfileappender Log4j.appender.bbsappender.file=logs/bbs.log
LOG4J.APPENDER.BBSAPPENDER.MAXFILESIZE=20MB log4j.appender.bbsappender.maxbackupindex=100
Log4j.appender.bbsappender.layout=org.apache.log4j.patternlayout Log4j.appender.bbsappender.layout.conversionpattern=%d{yyyy-mm-dd hh:mm:sss} %-5p [%t] %m (%c.%L)%n # Send the number log log4j.logger.com.ucweb.ka=warn,kaappender Log4j.additivity.com.ucweb.ka=false log4j.appender.kaAppender=
Org.apache.log4j.RollingFileAppender Log4j.appender.kaappender.file=logs/ka.log
LOG4J.APPENDER.KAAPPENDER.MAXFILESIZE=20MB log4j.appender.kaappender.maxbackupindex=100
Log4j.appender.kaappender.layout=org.apache.log4j.patternlayout
Log4j.appender.kaappender.layout.conversionpattern=%d{yyyy-mm-dd hh:mm:sss} %-5p [%t] %m (%c.%L)%n   #门户日志 Log4j.logger.com.ucweb.game=warn,gameappender LOG4J.ADDITIVITY.COM.UCWEB.GAme=false Log4j.appender.gameappender=org.apache.log4j.rollingfileappender Log4j.appender.gameappender.file=logs
/game.log LOG4J.APPENDER.GAMEAPPENDER.MAXFILESIZE=20MB log4j.appender.gameappender.maxbackupindex=100
Log4j.appender.gameappender.layout=org.apache.log4j.patternlayout Log4j.appender.gameappender.layout.conversionpattern=%d{yyyy-mm-dd hh:mm:sss} %-5p [%t] %m (%c.%L)%n
2) Turn off the print log in the parent logger, and configure layout by Log4j.additivity Configuration 3, as far as possible output the following information: timestamp, thread name, class, method, log content, line number 4) online environment to prohibit the output log to the console Appender; 5) On-line environment, log-level group number is warn above level; Log Printing considerations

At present, the JWS framework is to provide log output through the SLF4J log interface, and it is recommended to follow the following log coding specification when exporting logs:

Rule 1"in exceptional cases, get the log sample unified using SLF4J loggerfactory the following signature method to obtain, in order to facilitate the subsequent switch log implementation, but also unified coding style:

Org.slf4j.LoggerFactory corresponds to the following signature method: public static Logger GetLogger (Class clazz)
 and corresponding log instances are best defined as static final
 private static final Logger Logger = Loggerfactory.getlogger (Logdemo.class);

Rule 2"prohibits doping business logic operations in print log code, especially modifying caching operations: In the following example, Logicmap is a business cache, and the coder intended to delete one element of the cache and record it through the log. However, when the system log level is adjusted to warn above, the remove operation will not execute, which will result in fatal error and difficult to locate

Logicmap.put ("Danger", "danger");
if (logger.iswarnenabled ())
{
     Logger.warn ("Rmv A value:{}", Logicmap.remove ("Danger"));

Rule 3"to eat an exception, be sure to print detailed stack information (special no need to print, need to add comments in code), such as only the exception to do the packaging, and then thrown out again, it is prohibited to print stack information, print a maximum of simple positioning information; exception information must be printed with the error level:

        try {
            //May throw exception logic
        } catch (Exception e) {
            //here to eat the exception, you need to print the exception stack
            logger.error ("", e);
        }

rule 4"Direct output log information in the loop, you can first through the StringBuilder (not stringbuffer) to do log collection operations, and then output the log, such as the output log content is too long, need to do truncation

        StringBuilder sb = new StringBuilder ();
        string[] businesstmp = new String[bus_len];
        for (
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.