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