aa24171b42583d7bd44bbcfb1bd42a1af4076c7a
[org.ibex.core.git] / src / org / xwt / util / Log.java
1 // Copyright (C) 2003 Adam Megacz <adam@xwt.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.xwt.util;
9 import org.xwt.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 = true;
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     /** log a message with the current JavaScript sourceName/line */
26     public static void logJS(Object o, Object message) { logJS(message); }
27     public static void logJS(Object message) { log(JS.getSourceName() + ":" + JS.getLine(), message); }
28
29     /** message can be a String or a Throwable */
30     public static synchronized void echo(Object o, Object message) { log(o, message, ECHO); }
31     public static synchronized void debug(Object o, Object message) { log(o, message, DEBUG); }
32     public static synchronized void info(Object o, Object message) { log(o, message, INFO); }
33     public static synchronized void warn(Object o, Object message) { log(o, message, WARN); }
34     public static synchronized void error(Object o, Object message) { log(o, message, ERROR); }
35
36     // these two logging levels serve ONLY to change the color; semantically they are the same as DEBUG
37     private static final int DIAGNOSTIC = -2;
38     private static final int ECHO = -1;
39
40     // the usual log4j levels, minus FAIL (we just throw an Error in that case)
41     private static final int DEBUG = 0;
42     private static final int INFO = 1;
43     private static final int WARN = 2;
44     private static final int ERROR = 3;
45
46     private static final int BLACK = 30;
47     private static final int BLUE = 34;
48     private static final int GREEN = 32;
49     private static final int CYAN = 36;
50     private static final int RED = 31;
51     private static final int PURPLE = 35;
52     private static final int BROWN = 33;
53     private static final int GRAY = 37;
54
55     private static String color(int color, boolean bright, String s) {
56         return
57             "" + ((char)27) + "[" + (bright?1:0) + ";" + color + "m" +
58             s +
59             ((char)27) + "[0m";
60     }
61
62     private static String lastClassName = null;
63     private static synchronized void log(Object o, Object message, int level) {
64         if (firstMessage && !logDates) {
65             firstMessage = false;
66             System.err.println("===========================================================================");
67             String incolor = color ? "in " +
68                 color(BLUE, true, "c") +
69                 color(RED, true, "o") +
70                 color(CYAN, true, "l") +
71                 color(GREEN, true, "o") +
72                 color(PURPLE, true, "r") + " " : "";
73             log(Log.class, "Logging enabled at " + new java.util.Date() + " " + incolor);
74         }
75
76         String classname;
77         if (o instanceof Class) classname = ((Class)o).getName();
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.indexOf('.') != -1) classname = classname.substring(classname.lastIndexOf('.') + 1);
85         if (classname.length() > (logDates ? 14 : 20)) classname = classname.substring(0, (logDates ? 14 : 20));
86         while (classname.length() < (logDates ? 14 : 20)) classname = " " + classname;
87         classname = classname + (classname.trim().length() == 0 ? "  " : ": ");
88         classname = color(GRAY, true, classname);
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(color(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, level);
114             } catch (IOException e) {
115                 System.err.println(color(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 = color(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 = BLACK; 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 + color(levelcolor, bright, str.substring(0, str.indexOf('\n'))));
138             classname = logDates ? "                " : "                      ";
139             str = str.substring(str.indexOf('\n') + 1);
140         }
141         System.err.println(classname + color(levelcolor, bright, str));
142     }
143
144     public static void recursiveLog(String indent, String name, Object o) throws JSExn {
145         if (!name.equals("")) name += " : ";
146
147         if (o == null) {
148             Log.logJS(indent + name + "<null>");
149
150         } else if (o instanceof JSArray) {
151             Log.logJS(indent + name + "<array>");
152             JSArray na = (JSArray)o;
153             for(int i=0; i<na.length(); i++)
154                 recursiveLog(indent + "  ", i + "", na.elementAt(i));
155
156         } else if (o instanceof JS) {
157             Log.logJS(indent + name + "<object>");
158             JS s = (JS)o;
159             Enumeration e = s.keys();
160             while(e.hasMoreElements()) {
161                 Object key = e.nextElement();
162                 if (key != null)
163                     recursiveLog(indent + "  ", key.toString(),
164                                  (key instanceof Integer) ?
165                                  s.get(((Integer)key)) : s.get(key.toString()));
166             }
167         } else {
168             Log.logJS(indent + name + o);
169
170         }
171     }
172
173 }