Java Log Specification

Source: Internet
Author: User
Tags log4j

Objective

A program that runs in a production environment without logs is very scary for defenders, and there are too many messy and pointless logs to be frustrating. If there is a problem with the program, the possible cause of the problem from the log is frustrating. This article is about how to write a log in a Java program.

There are generally two types of logs: Business log and Exception log, using logs we want to achieve the following goals:

  1. Record and monitor the operation of the program;
  2. Detailed knowledge of the operating state of the program, if necessary;
  3. Minimal impact on system performance Java log framework

    There are too many log frames in Java ...

      1. log4j   or   log4j 2  -Apache Open Source project, by using log4j, We can control the log information delivery destination is the console, files, GUI components, even the interface server, NT Event recorder, UNIX syslog daemon, etc., the user can also control the output format of each log, by defining the level of each log information, The user is able to control the log generation process more carefully. These can be configured flexibly through a configuration file (XML or properties file) without the need to modify the program code. Log4j 2 is an upgrade of the predecessor, referring to many features of Logback;
      2. logback  -Logback is another open source journaling component designed by the founder of Log4j. The Logback is currently divided into three modules: Logback-core,logback-classic and logback-access. The Logback-core is the base module for the other two modules. Logback-classic is an improved version of log4j. In addition logback-classic full implementation of the SLF4J API allows you to easily change to other journaling systems such as log4j or JDK14 Logging;
      3. java.util.logging  -JDK built-in log interface and implementation, the function is relatively simple; the
      4. slf4j  -SLF4J provides a simple, unified interface for a variety of logging APIs. This allows the user to configure their desired Logging API implementation at deployment time;
      5. Apache Commons Logging  -Apache Commons Logging (JCL) Want to solve the problem and slf4j similar.

    The result of too many options is the choice of difficult disease, my view is not the best, only the most suitable. It may be more appropriate to choose Logback or implement your own high-performance logging API in a more focused area of performance, and in projects that have already used log4j, it may be more appropriate to continue using the project if no problem is found; I usually choose to use SLF4J in my project. If you do not want to have dependencies, use a log interface that is already provided by java.util.logging or the framework container.

    3.Java Log Best practices define log variables

    Log variables tend to be constant, preferably defined as final static, with uppercase variable names.

    Log rating

    Java's log framework generally provides the following log levels, by default open info level, that is, the debug,trace level of logs in the production environment will not output, in the development and testing environment can be opened by different log profiles debug level.

      1. Fatal -serious, resulting in a service interruption error;
      2. Error-Other error run-time errors;
      3. warn -warning message, such as a program called an expiring interface, improper use of the interface, the running state is not expected, but still can continue processing, etc.;
      4. Info -meaningful event information such as program start, Shutdown event, request event, etc.;
      5. Debug-debugging information to record detailed business processing to which step, as well as the current variable state;
      6. Trace-more detailed tracking information;

    In the program to use the appropriate log rating:

    1Logger.debug ("Entering getting content");2String content =cachemanager.getcachedcontent ();3 if(Content = =NULL){4 5         //use warn because the program can continue to execute, but similar warnings may indicate that the caching service is unavailable, and it is worth noting6Logger.warn ("Got empty content from Cache,need perform database lookup");7 8Connection conn =connectionfactory.getconnection ();9         if(conn=NULL) {TenLogger.error ("Can ' t get database connection, failed to return content");//try to provide detailed information, know the cause of the error, but not simply write Logger.error ("failed") One}Else{ A           Try{     -Content =conn.query (...);  -}Catch(IOException e) { the                        //exception to log the error stack -Logger.error ("Failed to perform database lookup", e); -}finally{ - connectionfactory.releaseconnection (conn); +                      } -                } + }   A //When you are debugging, you can know how the method returned. atLogger.debug ("Returning content:" +content); - returnContent
    Basic Logger Coding Specifications

1. Typically only one logger object is used in an object, logger should be static final , and private final will only be used if a few need to pass logger in the constructor.

Static final Logger_log=loggerfactory.getlogger (Main.  Class);

2. Output all throwable information for exceptions, as Logger.error (msg) and Logger.error (Msg,e.getmessage ()) This method of logging output loses the most important stacktrace information.

void foo () {     try  {            //do  something...      } Catch (Exception e) {          //  error          / / error           // correct       }}

3. Logging is not allowed and an exception is thrown because the log is logged more than once, allowing logging only once.

void throws logexception{     try{         // do something...     } Catch (Exception e) {          _log.error ("Bad things:", e);           Throw New Logexception ("Bad things:", E);       }}

4. System print (including SYSTEM.OUT.PRINTLN and SYSTEM.ERROR.PRINTLN) statements are not allowed .

void foo () {        try{               // do something...        } Catch (Exception e) {              //  error             /   /Error             _log.error ("Bad Things: ", e);  // correct           } }

5. Printstacktrace is not allowed .

void foo () {     try  {             // do something...     } Catch (Exception e) {            //  error            // correct          }}

6. Log performance considerations, if the code is the core code, the execution frequency is very high, then the output log is recommended to increase the judgment, especially the low level output <debug, info, warn>.

There are too many debug logs that can affect performance, and one way to improve this is to:

if (logger.isdebugenabled ()) {    Logger.debug ("Returning content:" + content);}

But a better approach is the best practice provided by SLF4J:

Logger.debug ("Returning content: {}", content);

On the one hand can reduce the cost of the parameter construction, on the other hand do not write two lines of code.

7. Meaningful logs

Usually in the program log to record some more meaningful status data: program start, the time of exit, the time of program running, the execution progress of time-consuming program, the state change of important variables.

In addition, in the public log to avoid the printing program debugging or prompt information.

FAQ: Reference

1.7 Good Rules to Log Exceptions

2.5 Common Log Mistakes

Log of the 3.Java program

Java Log Specification

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.