2012年8月15日 星期三

[ Java 文章收集 ] JAVA LOGGING API - TUTORIAL

來源自 這裡 
Preface : 
This article describes how to use the Logging API in Java programs. It includes an example for creating a HTML logger. 

OVERVIEW : 
- LOGGING IN JAVA 
The JDK contains the "Java Logging API". Via a logger you can save text to a central place to report on errors, provide additional information about your program, etc. This logging API allows to configure how messages are written by which class with which priority. 

- CREATE A LOGGER 
The package java.util.logging provides the logging capabilities via the class Logger. To create a logger in your Java coding : 
  1. import java.util.logging.Logger;  
  2.   
  3. private final static Logger LOGGER = Logger.getLogger(MyClass.class .getName());   
- LEVEL 
The log levels define the severity of a message. The class Level is used to define which messages should be written to the log. The following lists the Log Levels in descending order : 
* SEVERE (highest)
* WARNING
* INFO
* CONFIG
* FINE
* FINER
* FINEST

In addition to that you have also the levels OFF and ALL to turn the logging of or to log everything. For example the following will set the logger to level info which means all messages with severe, warning and info will be logged : 
  1. LOGGER.setLevel(Level.INFO);   
- HANDLER 
Each logger can have access to several handler. The handler receives the log message from the logger and exports it to a certain target. A handler can be turn off withsetLevel(Level.OFF) and turned on with setLevel(...). You have several standard handler, e.g. 
* ConsoleHandler: Write the log message to console
* FileHandler: Writes the log message to file

Log Levels INFO and higher will be automatically written to the console. 

- FORMATTER 
Each handlers output can be configured with a formatter. Below are Available formatters : 
* SimpleFormatter Generate all messages as text
* XMLFormatter Generates XML output for the log messages 

You can also build your own formatter. The following is an example of a formatter which will use create HTML output : 

  1. package test.logging;

    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.logging.Formatter;
    import java.util.logging.Handler;
    import java.util.logging.Level;
    import java.util.logging.LogRecord;

    //This custom formatter formats parts of a log record to a single line
    public class MyHtmlFormatter extends Formatter
    {
     // This method is called for every log records
     @Override
     public String format(LogRecord rec)
     {
       StringBuffer buf = new StringBuffer(1000);
       // Bold any levels >= WARNING
       buf.append("<tr>");
       buf.append("<td>");

       if (rec.getLevel().intValue() >= Level.WARNING.intValue())
       {
         buf.append("<b><font color='red'>");
         buf.append(rec.getLevel());
         buf.append("</font></b>");
       } else
       {
         buf.append(rec.getLevel());
       }
       buf.append("</td>");
       buf.append("<td>");
       buf.append(calcDate(rec.getMillis()));
       buf.append(' ');
       buf.append(formatMessage(rec));
       buf.append('\n');
       buf.append("</td>");
       buf.append("</tr>\n");
       return buf.toString();
     }

     private String calcDate(long millisecs)
     {
       SimpleDateFormat date_format = new SimpleDateFormat("MMM dd,yyyy HH:mm");
       Date resultdate = new Date(millisecs);
       return date_format.format(resultdate);
     }

     // This method is called just after the handler using this
     // formatter is created
     @Override
     public String getHead(Handler h)
     {
       return "<HTML>\n<HEAD>\n"   (new Date())   "\n</HEAD>\n<BODY>\n<PRE>\n"
             "<table border>\n  "
             "<tr><th>Time</th><th>Log Message</th></tr>\n";
     }

     // This method is called just after the handler using this
     // formatter is closed
     @Override
     public String getTail(Handler h)
     {
       return "</table>\n  </PRE></BODY>\n</HTML>\n";
     }
    }
- LOG MANAGER 
The log manager is responsible for creating and managing the logger and the maintenance of the configuration. We could set the logging level for a package, or even a set of packages, by calling the LogManager.setLevel(String name, Level level) method. So, for example, we could set the logging level of all loggers "logging" to Level.FINE by making this call : 
  1. LogManager.getLogManager().setLevel("logging", Level.FINE);  
- BEST PRACTICES 
It is common practice to use the fully qualified name of each class whose activity is being logged as a message category because this allows developers to fine-tune log settings for each class. Using the fully qualified class name of your class as the name of your Logger is the approach recommended by the Logging API documentation. 

EXAMPLE : 
Create your own formatter : 
- MyHtmlFormatter.java : Refer to previous FORMATTER  example.

Initialize the logger : 
- MyLogger.java : 
  1. package test.logging;  
  2.   
  3. import java.io.IOException;  
  4. import java.util.logging.FileHandler;  
  5. import java.util.logging.Formatter;  
  6. import java.util.logging.Level;  
  7. import java.util.logging.Logger;  
  8. import java.util.logging.SimpleFormatter;  
  9.   
  10. public class MyLogger {  
  11.     static private FileHandler fileTxt;  
  12.     static private SimpleFormatter formatterTxt;  
  13.   
  14.     static private FileHandler fileHTML;  
  15.     static private Formatter formatterHTML;  
  16.   
  17.     static public void setup() throws IOException {  
  18.         // Create Logger  
  19.         Logger logger = Logger.getLogger("");  
  20.         logger.setLevel(Level.INFO);  
  21.         fileTxt = new FileHandler("Logging.txt");  
  22.         fileHTML = new FileHandler("Logging.html");  
  23.   
  24.         // Create txt Formatter  
  25.         formatterTxt = new SimpleFormatter();  
  26.         fileTxt.setFormatter(formatterTxt);  
  27.         logger.addHandler(fileTxt);  
  28.   
  29.         // Create HTML Formatter  
  30.         formatterHTML = new MyHtmlFormatter();  
  31.         fileHTML.setFormatter(formatterHTML);  
  32.         logger.addHandler(fileHTML);  
  33.     }  
  34. }  
Use the logger : 
- UseLogger.java 
  1. package test.logging;  
  2.   
  3. import java.io.IOException;  
  4. import java.util.logging.Level;  
  5. import java.util.logging.Logger;  
  6.   
  7. public class UseLogger {  
  8.     // Always use the classname, this way you can refactor  
  9.     private final static Logger LOGGER = Logger.getLogger(UseLogger.class.getName());  
  10.   
  11.     public void writeLog() {  
  12.         // Set the LogLevel to Severe, only severe Messages will be written  
  13.         LOGGER.setLevel(Level.SEVERE);  
  14.         LOGGER.severe("Info Log");  
  15.         LOGGER.warning("Info Log");  
  16.         LOGGER.info("Info Log");  
  17.         LOGGER.finest("Really not important");  
  18.   
  19.         // Set the LogLevel to Info, severe, warning and info will be written  
  20.         // Finest is still not written  
  21.         LOGGER.setLevel(Level.INFO);  
  22.         LOGGER.severe("Severe Log");  
  23.         LOGGER.warning("Warn Log");  
  24.         LOGGER.info("Info Log");  
  25.         LOGGER.finest("Really not important");  
  26.     }  
  27.   
  28.     public static void main(String[] args) {  
  29.         UseLogger logger = new UseLogger();  
  30.         try {  
  31.             MyLogger.setup();  
  32.         } catch (IOException e) {  
  33.             e.printStackTrace();  
  34.             throw new RuntimeException("Problems with creating the log files");  
  35.         }  
  36.         logger.writeLog();  
  37.     }  
  38. }  
After execution, you will see two files being generated under working directory. The HTML file looks like : 
 

And the txt file : 
2012/8/16 下午 01:53:53 test.logging.UseLogger writeLog
嚴重的: Info Log
2012/8/16 下午 01:53:53 test.logging.UseLogger writeLog
嚴重的: Severe Log
2012/8/16 下午 01:53:53 test.logging.UseLogger writeLog
警告: Warn Log
2012/8/16 下午 01:53:53 test.logging.UseLogger writeLog
資訊: Info Log

SUPPLEMENT : 
記錄(Logging): 簡 介 Logging 
記錄(Logging): Logging 的層級 
記錄(Logging): Handler、 Formatter 
記錄(Logging): 自 訂 Formatter 
記錄(Logging): 自 訂 Handler 
記錄(Logging): 自 訂 Filter 
記錄(Logging): Logger 階層關係

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...