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