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