Debian Codegraph @

src/uk/me/parabola/log/UsefulFormatter.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2007 Steve Ratcliffe
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License version 2 as
6 * published by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 *
14 * Author: Steve Ratcliffe
15 * Create date: 08-Sep-2007
16 */
17 package uk.me.parabola.log;
18
19 import java.io.PrintWriter;
20 import java.io.StringWriter;
21 import java.util.Calendar;
22 import java.util.logging.Formatter;
23 import java.util.logging.Level;
24 import java.util.logging.LogRecord;
25
26 /**
27 * Prints the message all on one line, which amazingly is not the default
28 * behaviour in j.u.l, no wonder no one uses it.
29 *
30 * MUST be public whatever crazy static analyzers might say.
31 *
32 * @author Steve Ratcliffe
33 */
34 public class UsefulFormatter extends Formatter {
35 private boolean showTime = true;
36 private static final String lineSeparator = System.getProperty("line.separator");
37
38
39 public String format(LogRecord record) {
40 StringBuffer sb = new StringBuffer();
41
42 if (record.getLevel().intValue() <= Level.SEVERE.intValue()) {
43 if (showTime) {
44 long millis = record.getMillis();
45 Calendar cal = Calendar.getInstance();
46 cal.setTimeInMillis(millis);
47 sb.append(cal.get(Calendar.YEAR));
48 sb.append('/');
49 sb.append(fmt2(cal.get(Calendar.MONTH)+1));
50 sb.append('/');
51 sb.append(fmt2(cal.get(Calendar.DAY_OF_MONTH)));
52 sb.append(' ');
53 sb.append(fmt2(cal.get(Calendar.HOUR_OF_DAY)));
54 sb.append(':');
55 sb.append(fmt2(cal.get(Calendar.MINUTE)));
56 sb.append(':');
57 sb.append(fmt2(cal.get(Calendar.SECOND)));
58 sb.append(' ');
59 }
60
61 sb.append(record.getLevel().getLocalizedName());
62 sb.append(" (");
63 sb.append(shortName(record.getLoggerName()));
64 sb.append("): ");
65 }
66 sb.append(record.getMessage());
67
68 sb.append(lineSeparator);
69
70 Throwable t = record.getThrown();
71 if (t != null) {
72 StringWriter out = new StringWriter();
73 PrintWriter pw = new PrintWriter(out);
74 t.printStackTrace(pw);
75 sb.append(out.toString());
76 }
77 return sb.toString();
78 }
79
80 public void setShowTime(boolean showTime) {
81 this.showTime = showTime;
82 }
83
84 private String fmt2(int i) {
85 StringBuffer res = new StringBuffer(String.valueOf(i));
86 while (res.length() < 2) {
87 res.insert(0, '0');
88 }
89 return res.toString();
90 }
91
92 private String shortName(String name) {
93 int end = name.lastIndexOf('.');
94 if (end > 0) {
95 return name.substring(end+1);
96 } else
97 return name;
98 }
99 }