e90b77432e9bbd37f5e3d9431d0b0ffc1658509c
[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) classname = ((Class)o).getName();
75         else if (o instanceof String) classname = (String)o;
76         else classname = o.getClass().getName();
77
78         if (classname.equals(lastClassName)) classname = "";
79         else lastClassName = classname;
80         
81         if (classname.indexOf('.') != -1) classname = classname.substring(classname.lastIndexOf('.') + 1);
82         if (classname.length() > (logDates ? 14 : 20)) classname = classname.substring(0, (logDates ? 14 : 20));
83         while (classname.length() < (logDates ? 14 : 20)) classname = " " + classname;
84         classname = classname + (classname.trim().length() == 0 ? "  " : ": ");
85         classname = colorize(GRAY, true, classname);
86         classname = classname.replace('$', '.');
87
88         if (logDates) {
89             Date d = new Date();
90             if (lastDate == null || d.getYear() != lastDate.getYear() || d.getMonth() != lastDate.getMonth() || d.getDay() != lastDate.getDay()) {
91                 String now = new java.text.SimpleDateFormat("EEE dd MMM yyyy").format(d);
92                 System.err.println();
93                 System.err.println(colorize(GRAY, false, "=== " + now + " =========================================================="));
94             }
95             java.text.DateFormat df = new java.text.SimpleDateFormat("[EEE HH:mm:ss] ");
96             classname = df.format(d) + classname;
97             lastDate = d;
98         }
99
100
101         if (message instanceof Throwable) {
102             if (level < ERROR) level = WARN;
103             ByteArrayOutputStream baos = new ByteArrayOutputStream();
104             ((Throwable)message).printStackTrace(new PrintStream(baos));
105             byte[] b = baos.toByteArray();
106             BufferedReader br = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(b)));
107             String s = null;
108             try {
109                 String m = "";
110                 while((s = br.readLine()) != null) m += s + "\n";
111                 log(o, m.substring(0, m.length() - 1), level);
112             } catch (IOException e) {
113                 System.err.println(colorize(RED, true, "Logger: exception thrown by ByteArrayInputStream -- this should not happen"));
114             }
115             return;
116         }
117
118         String str = message.toString();
119         while(str.indexOf('\t') != -1)
120             str = str.substring(0, str.indexOf('\t')) + "    " + str.substring(str.indexOf('\t') + 1);
121
122         classname = colorize(GRAY, false, classname);
123         int levelcolor = GRAY;
124         boolean bright = true;
125         switch (level) {
126             case DIAGNOSTIC:  levelcolor = GREEN; bright = false; break;
127             case ECHO:        levelcolor = BLUE;  bright = true;  break;
128             case DEBUG:       levelcolor = BROWN; bright = true;  break;
129             case INFO:        levelcolor = GRAY;  bright = false; break;
130             case WARN:        levelcolor = BROWN; bright = false; break;
131             case ERROR:       levelcolor = RED;   bright = true;  break;
132         }
133
134         while(str.indexOf('\n') != -1) {
135             System.err.println(classname + colorize(levelcolor, bright, str.substring(0, str.indexOf('\n'))));
136             classname = logDates ? "                " : "                      ";
137             classname = colorize(GRAY,false,classname);
138             str = str.substring(str.indexOf('\n') + 1);
139         }
140         System.err.println(classname + colorize(levelcolor, bright, str));
141     }
142
143     public static void recursiveLog(String indent, String name, Object o) throws JSExn {
144         if (!name.equals("")) name += " : ";
145
146         if (o == null) {
147             JS.log(indent + name + "<null>");
148
149         } else if (o instanceof JSArray) {
150             JS.log(indent + name + "<array>");
151             JSArray na = (JSArray)o;
152             for(int i=0; i<na.length(); i++)
153                 recursiveLog(indent + "  ", i + "", na.elementAt(i));
154
155         } else if (o instanceof JS) {
156             JS.log(indent + name + "<object>");
157             JS s = (JS)o;
158             Enumeration e = s.keys();
159             while(e.hasMoreElements()) {
160                 Object key = e.nextElement();
161                 if (key != null)
162                     recursiveLog(indent + "  ", key.toString(),
163                                  (key instanceof Integer) ?
164                                  s.get(((Integer)key)) : s.get(key.toString()));
165             }
166         } else {
167             JS.log(indent + name + o);
168
169         }
170     }
171
172 }