View Javadoc

1   /*
2    * $Id ConsoleFormatter.java $
3    *
4    */
5   
6   package org.astrogrid.log;
7   
8   import java.io.PrintWriter;
9   import java.io.StringWriter;
10  import java.text.SimpleDateFormat;
11  import java.util.Date;
12  import java.util.logging.Formatter;
13  import java.util.logging.Level;
14  import java.util.logging.LogRecord;
15  
16  /***
17   * For formatting errors to console nicely
18   *
19   * @author M Hill
20   */
21  
22  public class ConsoleFormatter extends Formatter
23  {
24  
25     /***
26      * Format the given log record and return the formatted string.
27      * <p>
28      * The resulting formatted String will normally include a
29      * localized and formated version of the LogRecord's message field.
30      * The Formatter.formatMessage convenience method can (optionally)
31      * be used to localize and format the message field.
32      *
33      * @param record the log record to be formatted.
34      * @return the formatted log record
35      */
36     public String format(LogRecord record)
37     {
38        Date d = new Date(record.getMillis());
39  
40        SimpleDateFormat format = new SimpleDateFormat("yy-MM-DD HH:mm:ss");
41  
42        String msg = format.format(d)+" "+record.getLevel()+" "+record.getMessage();
43  
44        if (record.getThrown() != null)
45        {
46           if (record.getLevel().intValue() < Level.SEVERE.intValue())
47           {
48              msg = msg + " ("+record.getThrown()+")\n";
49           }
50           else
51           {
52              StringWriter writer = new StringWriter();
53              record.getThrown().printStackTrace(new PrintWriter(writer));
54              msg = msg + "\n\n"+writer.toString();
55           }
56        }
57        else
58        {
59           msg = msg +"\n";
60        }
61  
62        return msg;
63     }
64  
65  
66  }
67  
68  /*
69  $Log: ConsoleFormatter.java,v $
70  Revision 1.3  2003/09/15 11:47:14  mch
71  Fixes to handle the built-in loggers hidden console output
72  
73  Revision 1.2  2003/09/14 22:34:02  mch
74  Nicer warning messages
75  
76  Revision 1.1  2003/09/11 17:53:54  mch
77  Added logTo() methods and made sure trace can go to console
78  
79  */