added smarter exception logging
[org.ibex.util.git] / src / org / ibex / util / Log.java
1 // Copyright (C) 2003 Adam Megacz <adam@ibex.org> all rights reserved.
2 //
3 // You may modify, copy, and redistribute this code under the terms of
4 // the GNU Library Public License version 2.1, with the exception of
5 // the portion of clause 6a after the semicolon (aka the "obnoxious
6 // relink clause")
7
8 package org.ibex.util;
9 import org.ibex.js.*;
10 import java.io.*;
11 import java.util.*;
12 import java.net.*;
13
14 /** easy to use logger */
15 public class Log {
16
17     public static boolean on            = System.getProperty("ibex.log.on", "true").equals("true");
18     public static boolean color         = System.getProperty("ibex.log.color", "true").equals("true");
19     public static boolean verbose       = System.getProperty("ibex.log.verbose", "false").equals("true");
20     public static boolean logDates      = System.getProperty("ibex.log.dates", "false").equals("true");
21     public static boolean notes         = System.getProperty("ibex.log.notes.on", "true").equals("true");
22     public static boolean stackTraces   = System.getProperty("ibex.log.stackTraces", "true").equals("true");
23     public static int maximumNoteLength = Integer.parseInt(System.getProperty("ibex.log.notes.maximumLength", (1024 * 32)+""));
24     public static boolean rpc           = false;
25     public static Date lastDate = null;
26
27     public static PrintStream logstream = System.err;
28
29     public static void flush() { logstream.flush(); }
30     public static void email(String address) { throw new Error("FIXME not supported"); }
31     public static void file(String filename) throws IOException {
32         // FIXME security
33         logstream = new PrintStream(new FileOutputStream(filename));
34     }
35     public static void tcp(String host, int port) throws IOException {
36         // FIXME security
37         logstream = new PrintStream(new Socket(InetAddress.getByName(host), port).getOutputStream());
38     }
39
40     private static Hashtable threadAnnotations = new Hashtable();
41     public static void setThreadAnnotation(String s) { threadAnnotations.put(Thread.currentThread(), s); }
42
43     /** 
44      *  Notes can be used to attach log messages to the current thread
45      *  if you're not sure you want them in the log just yet.
46      *  Originally designed for retroactively logging socket-level
47      *  conversations only if an error is encountered
48      */
49     public static void note(String s) {
50         if (!notes) return;
51         StringBuffer notebuf = notebuf();
52         notebuf.append(s);
53         if (notebuf.length() > maximumNoteLength) {
54             notebuf.reverse();
55             notebuf.setLength(maximumNoteLength * 3 / 4);
56             notebuf.reverse();
57         }
58     }
59     public static void clearnotes() { if (!notes) return; notebuf().setLength(0); }
60     private static Hashtable notebufs = new Hashtable();
61     public static StringBuffer notebuf() {
62         StringBuffer ret = (StringBuffer)notebufs.get(Thread.currentThread());
63         if (ret == null) {
64             ret = new StringBuffer(16 * 1024);
65             notebufs.put(Thread.currentThread(), ret);
66         }
67         return ret;
68     }
69
70     /** true iff nothing has yet been logged */
71     public static boolean firstMessage = true;
72
73     /** message can be a String or a Throwable */
74     public static synchronized void echo(Object o, Object message) { log(o, message, ECHO); }
75     public static synchronized void diag(Object o, Object message) { log(o, message, DIAGNOSTIC); }
76     public static synchronized void debug(Object o, Object message) { log(o, message, DEBUG); }
77     public static synchronized void info(Object o, Object message) { log(o, message, INFO); }
78     public static synchronized void warn(Object o, Object message) { log(o, message, WARN); }
79     public static synchronized void error(Object o, Object message) { log(o, message, ERROR); }
80
81     // these two logging levels serve ONLY to change the color; semantically they are the same as DEBUG
82     private static final int DIAGNOSTIC = -2;
83     private static final int ECHO = -1;
84
85     // the usual log4j levels, minus FAIL (we just throw an Error in that case)
86     public static final int DEBUG = 0;
87     public static final int INFO = 1;
88     public static final int WARN = 2;
89     public static final int ERROR = 3;
90     public static final int SILENT = Integer.MAX_VALUE;
91     public static int level = INFO;
92
93     private static final int BLUE = 34;
94     private static final int GREEN = 32;
95     private static final int CYAN = 36;
96     private static final int RED = 31;
97     private static final int PURPLE = 35;
98     private static final int BROWN = 33;
99     private static final int GRAY = 37;
100     
101     private static String colorize(int color, boolean bright, String s) {
102         if (!Log.color) return s;
103         return
104             "\033[40;" + (bright?"1;":"") + color + "m" +
105             s +
106             "\033[0m";
107     }
108
109     private static String lastClassName = null;
110     private static synchronized void log(Object o, Object message, int level) {
111         if (level < Log.level) return;
112         if (firstMessage && !logDates) {
113             firstMessage = false;
114             logstream.println(colorize(GREEN, false, "==========================================================================="));
115
116             // FIXME later: causes problems with method pruning
117             //diag(Log.class, "Logging enabled at " + new java.util.Date());
118
119             if (color) diag(Log.class, "logging messages in " +
120                 colorize(BLUE, true, "c") +
121                 colorize(RED, true, "o") +
122                 colorize(CYAN, true, "l") +
123                 colorize(GREEN, true, "o") +
124                 colorize(PURPLE, true, "r"));
125         }
126
127         String classname;
128         if (o instanceof Class) {
129             classname = ((Class)o).getName();
130             if (classname.indexOf('.') != -1) classname = classname.substring(classname.lastIndexOf('.') + 1);
131         }
132         else if (o instanceof String) classname = (String)o;
133         else classname = o.getClass().getName();
134
135         if (classname.equals(lastClassName)) classname = "";
136         else lastClassName = classname;
137         
138         if (classname.length() > (logDates ? 14 : 20)) classname = classname.substring(0, (logDates ? 14 : 20));
139         while (classname.length() < (logDates ? 14 : 20)) classname = " " + classname;
140         classname = classname + (classname.trim().length() == 0 ? "  " : ": ");
141         classname = colorize(GRAY, true, classname);
142         classname = classname.replace('$', '.');
143
144         if (logDates) {
145             Date d = new Date();
146             if (lastDate == null || d.getYear() != lastDate.getYear() || d.getMonth() != lastDate.getMonth() || d.getDay() != lastDate.getDay()) {
147                 String now = new java.text.SimpleDateFormat("EEE dd MMM yyyy").format(d);
148                 logstream.println();
149                 logstream.println(colorize(GRAY, false, "=== " + now + " =========================================================="));
150             }
151             java.text.DateFormat df = new java.text.SimpleDateFormat("[EEE HH:mm:ss] ");
152             classname = df.format(d) + classname;
153             lastDate = d;
154         }
155
156         String annot = (String)threadAnnotations.get(Thread.currentThread());
157         if (annot != null) classname += annot;
158
159         if (message instanceof Throwable) {
160             if (level < ERROR) level = WARN;
161             ByteArrayOutputStream baos = new ByteArrayOutputStream();
162             ((Throwable)message).printStackTrace(new PrintStream(baos));
163             if (notes && notebuf().length() > 0) {
164                 PrintWriter pw = new PrintWriter(baos);
165                 pw.println();
166                 pw.println("Thread notes:");
167                 pw.println(notebuf().toString());
168                 clearnotes();
169                 pw.flush();
170             }
171             byte[] b = baos.toByteArray();
172             BufferedReader br = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(b)));
173             try {
174                 if (stackTraces) {
175                     String s = null;
176                     String m = "";
177                     while((s = br.readLine()) != null) m += s + "\n";
178                     if (m.length() > 0) log(o, m.substring(0, m.length() - 1), level);
179                 } else {
180                     message = br.readLine();
181                     String s = br.readLine();
182                     if (s.indexOf('(') != -1) message = message + " " + s.substring(s.indexOf('('));
183                     log(o, message, level);
184                 }
185                 lastClassName = "";
186             } catch (IOException e) {
187                 // FEATURE: use org.ibex.io.Stream's here
188                 logstream.println(colorize(RED, true, "Logger: exception thrown by ByteArrayInputStream;" +
189                                            " this should not happen"));
190             }
191             return;
192         }
193
194         String str = message.toString();
195         if (str.indexOf('\n') != -1) lastClassName = "";
196         while(str.indexOf('\t') != -1)
197             str = str.substring(0, str.indexOf('\t')) + "    " + str.substring(str.indexOf('\t') + 1);
198
199         classname = colorize(GRAY, false, classname);
200         int levelcolor = GRAY;
201         boolean bright = true;
202         switch (level) {
203             case DIAGNOSTIC:  levelcolor = GREEN; bright = false; break;
204             case ECHO:        levelcolor = BLUE;  bright = true;  break;
205             case DEBUG:       levelcolor = BROWN; bright = true;  break;
206             case INFO:        levelcolor = GRAY;  bright = false; break;
207             case WARN:        levelcolor = BROWN; bright = false; break;
208             case ERROR:       levelcolor = RED;   bright = true;  break;
209         }
210
211         while(str.indexOf('\n') != -1) {
212             logstream.println(classname + colorize(levelcolor, bright, str.substring(0, str.indexOf('\n'))));
213             classname = logDates ? "                " : "                      ";
214             classname = colorize(GRAY,false,classname);
215             str = str.substring(str.indexOf('\n') + 1);
216         }
217         logstream.println(classname + colorize(levelcolor, bright, str));
218     }
219
220     public static void recursiveLog(String indent, String name, Object o) throws JSExn {
221         if (!name.equals("")) name += " : ";
222
223         if (o == null) {
224             JS.log(indent + name + "<null>");
225
226         } else if (o instanceof JSArray) {
227             JS.log(indent + name + "<array>");
228             JSArray na = (JSArray)o;
229             for(int i=0; i<na.length(); i++)
230                 recursiveLog(indent + "  ", i + "", na.elementAt(i));
231
232         } else if (o instanceof JS) {
233             JS.log(indent + name + "<object>");
234             JS s = (JS)o;
235             Enumeration e = s.keys();
236             while(e.hasMoreElements()) {
237                 Object key = e.nextElement();
238                 if (key != null)
239                     recursiveLog(indent + "  ", key.toString(),
240                                  (key instanceof Integer) ?
241                                  s.get(((Integer)key)) : s.get(key.toString()));
242             }
243         } else {
244             JS.log(indent + name + o);
245
246         }
247     }
248
249 }