added Log.setThreadAnnotation()
[org.ibex.core.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 = true;
18     public static boolean rpc = false;
19     public static boolean color = false;
20     public static boolean verbose = false;
21     public static boolean logDates = false;
22     public static Date lastDate = null;
23
24     public static PrintStream logstream = System.err;
25
26     public static void email(String address) { throw new Error("FIXME not supported"); }
27     public static void file(String filename) throws IOException {
28         // FIXME security
29         logstream = new PrintStream(new FileOutputStream(filename));
30     }
31     public static void tcp(String host, int port) throws IOException {
32         // FIXME security
33         logstream = new PrintStream(new Socket(InetAddress.getByName(host), port).getOutputStream());
34     }
35
36     private static Hashtable threadAnnotations = new Hashtable();
37     public static void setThreadAnnotation(String s) { threadAnnotations.put(Thread.currentThread(), s); }
38
39     /** true iff nothing has yet been logged */
40     public static boolean firstMessage = true;
41
42     /** message can be a String or a Throwable */
43     public static synchronized void echo(Object o, Object message) { log(o, message, ECHO); }
44     public static synchronized void diag(Object o, Object message) { log(o, message, DIAGNOSTIC); }
45     public static synchronized void debug(Object o, Object message) { log(o, message, DEBUG); }
46     public static synchronized void info(Object o, Object message) { log(o, message, INFO); }
47     public static synchronized void warn(Object o, Object message) { log(o, message, WARN); }
48     public static synchronized void error(Object o, Object message) { log(o, message, ERROR); }
49
50     // these two logging levels serve ONLY to change the color; semantically they are the same as DEBUG
51     private static final int DIAGNOSTIC = -2;
52     private static final int ECHO = -1;
53
54     // the usual log4j levels, minus FAIL (we just throw an Error in that case)
55     public static final int DEBUG = 0;
56     public static final int INFO = 1;
57     public static final int WARN = 2;
58     public static final int ERROR = 3;
59     public static final int SILENT = Integer.MAX_VALUE;
60     public static int level = INFO;
61
62     private static final int BLUE = 34;
63     private static final int GREEN = 32;
64     private static final int CYAN = 36;
65     private static final int RED = 31;
66     private static final int PURPLE = 35;
67     private static final int BROWN = 33;
68     private static final int GRAY = 37;
69     
70     private static String colorize(int color, boolean bright, String s) {
71         if (!Log.color) return s;
72         return
73             "\033[40;" + (bright?"1;":"") + color + "m" +
74             s +
75             "\033[0m";
76     }
77
78     private static String lastClassName = null;
79     private static synchronized void log(Object o, Object message, int level) {
80         if (level < Log.level) return;
81         if (firstMessage && !logDates) {
82             firstMessage = false;
83             logstream.println(colorize(GREEN, false, "==========================================================================="));
84
85             // FIXME later: causes problems with method pruning
86             //diag(Log.class, "Logging enabled at " + new java.util.Date());
87
88             if (color) diag(Log.class, "logging messages in " +
89                 colorize(BLUE, true, "c") +
90                 colorize(RED, true, "o") +
91                 colorize(CYAN, true, "l") +
92                 colorize(GREEN, true, "o") +
93                 colorize(PURPLE, true, "r"));
94         }
95
96         String classname;
97         if (o instanceof Class) {
98             classname = ((Class)o).getName();
99             if (classname.indexOf('.') != -1) classname = classname.substring(classname.lastIndexOf('.') + 1);
100         }
101         else if (o instanceof String) classname = (String)o;
102         else classname = o.getClass().getName();
103
104         if (classname.equals(lastClassName)) classname = "";
105         else lastClassName = classname;
106         
107         if (classname.length() > (logDates ? 14 : 20)) classname = classname.substring(0, (logDates ? 14 : 20));
108         while (classname.length() < (logDates ? 14 : 20)) classname = " " + classname;
109         classname = classname + (classname.trim().length() == 0 ? "  " : ": ");
110         classname = colorize(GRAY, true, classname);
111         classname = classname.replace('$', '.');
112
113         if (logDates) {
114             Date d = new Date();
115             if (lastDate == null || d.getYear() != lastDate.getYear() || d.getMonth() != lastDate.getMonth() || d.getDay() != lastDate.getDay()) {
116                 String now = new java.text.SimpleDateFormat("EEE dd MMM yyyy").format(d);
117                 logstream.println();
118                 logstream.println(colorize(GRAY, false, "=== " + now + " =========================================================="));
119             }
120             java.text.DateFormat df = new java.text.SimpleDateFormat("[EEE HH:mm:ss] ");
121             classname = df.format(d) + classname;
122             lastDate = d;
123         }
124
125         String annot = (String)threadAnnotations.get(Thread.currentThread());
126         if (annot != null) classname += annot;
127
128         if (message instanceof Throwable) {
129             if (level < ERROR) level = WARN;
130             ByteArrayOutputStream baos = new ByteArrayOutputStream();
131             ((Throwable)message).printStackTrace(new PrintStream(baos));
132             byte[] b = baos.toByteArray();
133             BufferedReader br = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(b)));
134             String s = null;
135             try {
136                 String m = "";
137                 while((s = br.readLine()) != null) m += s + "\n";
138                 if (m.length() > 0) log(o, m.substring(0, m.length() - 1), level);
139             } catch (IOException e) {
140                 logstream.println(colorize(RED, true, "Logger: exception thrown by ByteArrayInputStream -- this should not happen"));
141             }
142             lastClassName = "";
143             return;
144         }
145
146         String str = message.toString();
147         if (str.indexOf('\n') != -1) lastClassName = "";
148         while(str.indexOf('\t') != -1)
149             str = str.substring(0, str.indexOf('\t')) + "    " + str.substring(str.indexOf('\t') + 1);
150
151         classname = colorize(GRAY, false, classname);
152         int levelcolor = GRAY;
153         boolean bright = true;
154         switch (level) {
155             case DIAGNOSTIC:  levelcolor = GREEN; bright = false; break;
156             case ECHO:        levelcolor = BLUE;  bright = true;  break;
157             case DEBUG:       levelcolor = BROWN; bright = true;  break;
158             case INFO:        levelcolor = GRAY;  bright = false; break;
159             case WARN:        levelcolor = BROWN; bright = false; break;
160             case ERROR:       levelcolor = RED;   bright = true;  break;
161         }
162
163         while(str.indexOf('\n') != -1) {
164             logstream.println(classname + colorize(levelcolor, bright, str.substring(0, str.indexOf('\n'))));
165             classname = logDates ? "                " : "                      ";
166             classname = colorize(GRAY,false,classname);
167             str = str.substring(str.indexOf('\n') + 1);
168         }
169         logstream.println(classname + colorize(levelcolor, bright, str));
170     }
171
172     public static void recursiveLog(String indent, String name, Object o) throws JSExn {
173         if (!name.equals("")) name += " : ";
174
175         if (o == null) {
176             JS.log(indent + name + "<null>");
177
178         } else if (o instanceof JSArray) {
179             JS.log(indent + name + "<array>");
180             JSArray na = (JSArray)o;
181             for(int i=0; i<na.length(); i++)
182                 recursiveLog(indent + "  ", i + "", na.elementAt(i));
183
184         } else if (o instanceof JS) {
185             JS.log(indent + name + "<object>");
186             JS s = (JS)o;
187             Enumeration e = s.keys();
188             while(e.hasMoreElements()) {
189                 Object key = e.nextElement();
190                 if (key != null)
191                     recursiveLog(indent + "  ", key.toString(),
192                                  (key instanceof Integer) ?
193                                  s.get(((Integer)key)) : s.get(key.toString()));
194             }
195         } else {
196             JS.log(indent + name + o);
197
198         }
199     }
200
201 }