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