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