每日日报7月29日

1.今天学习了用Log4J记录异常日志信息

 代码目的:
 *       演示异常与记录日志的使用。
 *       java.util.logging工具将输出记录到日志中。
 *       日志消息被转发到已注册的 Handler 对象,
 *       该对象可以将消息转发到各种目的地,包括控制台、文件、OS 日志等等。 
 *       静态的Logger.getLogger方法创建了一个String参数相关联的Logger对象,通常与错误相关
 *       的包名和类名,这个Logger对象会将其输出发送到System.err。向Logger写入
 *       的最简单的方式就是直接调用与日志记录消息级别相关联的方法。
 *       
 *       为了产生日志记录字符串,我们要获取异常抛出处的栈轨迹,但是printStackTrace不会默认的产生
 *       字符串。为了获取字符串,我们需要使用重载的printStackTrace()方法,它接受一个java.io.PrintWriter
 *       对象作为参数,通过调用toString方法,就可以把输出抽取为一个String。
 *       
 * */

  1. //: exceptions/LoggingExceptions.java
  2.  
    // An exception that reports through a Logger.
  3.  
    import java.util.logging.*;
  4.  
    import java.io.*;
  5.  
     
  6.  
    class LoggingException extends Exception {
  7.  
    private static Logger logger =
  8.  
    Logger.getLogger( "LoggingException");
  9.  
    public LoggingException() {
  10.  
    StringWriter trace = new StringWriter();
  11.  
    //printStackTrace(PrintWriter)将此Throwable及其追踪输出到指定的PrintWriter
  12.  
    printStackTrace( new PrintWriter(trace));
  13.  
    logger.severe(trace.toString());
  14.  
    //logger.info(trace.toString());
  15.  
    }
  16.  
    }
  17.  
     
  18.  
    public class LoggingExceptions {
  19.  
    public static void main(String[] args) {
  20.  
    try {
  21.  
    throw new LoggingException();
  22.  
    } catch(LoggingException e) {
  23.  
    System.err.println( "Caught " + e);
  24.  
    }
  25.  
    try {
  26.  
    throw new LoggingException();
  27.  
    } catch(LoggingException e) {
  28.  
    System.err.println( "Caught " + e);
  29.  
    }
  30.  
    }
  31.  
    } /* Output: (85% match)
  32.  
    Aug 30, 2005 4:02:31 PM LoggingException <init>
  33.  
    SEVERE: LoggingException
  34.  
    at LoggingExceptions.main(LoggingExceptions.java:19)
  35.  
     
  36.  
    Caught LoggingException
  37.  
    Aug 30, 2005 4:02:31 PM LoggingException <init>
  38.  
    SEVERE: LoggingException
  39.  
    at LoggingExceptions.main(LoggingExceptions.java:24)
  40.  
     
  41.  
    Caught LoggingException
  42.  
    *///:~
    2.没有遇到问题
    3.明天打算学习类的继承和多态

猜你喜欢

转载自www.cnblogs.com/wanghaoning/p/13401296.html