preliminary core conversion
[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            = System.getProperty("ibex.log.on", "true").equals("true");
18     public static boolean color         = System.getProperty("ibex.log.color", "true").equals("true");
19     public static boolean verbose       = System.getProperty("ibex.log.verbose", "false").equals("true");
20     public static boolean logDates      = System.getProperty("ibex.log.dates", "false").equals("true");
21     public static boolean notes         = System.getProperty("ibex.log.notes.on", "true").equals("true");
22     public static int maximumNoteLength = Integer.parseInt(System.getProperty("ibex.log.notes.maximumLength", (1024 * 32)+""));
23     public static boolean rpc           = false;
24     public static Date lastDate = null;
25
26     public static PrintStream logstream = System.err;
27
28     public static void flush() { logstream.flush(); }
29     public static void email(String address) { throw new Error("FIXME not supported"); }
30     public static void file(String filename) throws IOException {
31         // FIXME security
32         logstream = new PrintStream(new FileOutputStream(filename));
33     }
34     public static void tcp(String host, int port) throws IOException {
35         // FIXME security
36         logstream = new PrintStream(new Socket(InetAddress.getByName(host), port).getOutputStream());
37     }
38
39     private static Hashtable threadAnnotations = new Hashtable();
40     public static void setThreadAnnotation(String s) { threadAnnotations.put(Thread.currentThread(), s); }
41
42     /** 
43      *  Notes can be used to attach log messages to the current thread
44      *  if you're not sure you want them in the log just yet.
45      *  Originally designed for retroactively logging socket-level
46      *  conversations only if an error is encountered
47      */
48     public static void note(String s) {
49         if (!notes) return;
50         StringBuffer notebuf = notebuf();
51         notebuf.append(s);
52         if (notebuf.length() > maximumNoteLength) {
53             notebuf.reverse();
54             notebuf.setLength(maximumNoteLength * 3 / 4);
55             notebuf.reverse();
56         }
57     }
58     public static void clearnotes() { if (!notes) return; notebuf().setLength(0); }
59     private static Hashtable notebufs = new Hashtable();
60     private static StringBuffer notebuf() {
61         StringBuffer ret = (StringBuffer)notebufs.get(Thread.currentThread());
62         if (ret == null) {
63             ret = new StringBuffer(16 * 1024);
64             notebufs.put(Thread.currentThread(), ret);
65         }
66         return ret;
67     }
68
69     /** true iff nothing has yet been logged */
70     public static boolean firstMessage = true;
71
72     /** message can be a String or a Throwable */
73     public static synchronized void echo(Object o, Object message) { log(o, message, ECHO); }
74     public static synchronized void diag(Object o, Object message) { log(o, message, DIAGNOSTIC); }
75     public static synchronized void debug(Object o, Object message) { log(o, message, DEBUG); }
76     public static synchronized void info(Object o, Object message) { log(o, message, INFO); }
77     public static synchronized void warn(Object o, Object message) { log(o, message, WARN); }
78     public static synchronized void error(Object o, Object message) { log(o, message, ERROR); }
79
80     // these two logging levels serve ONLY to change the color; semantically they are the same as DEBUG
81     private static final int DIAGNOSTIC = -2;
82     private static final int ECHO = -1;
83
84     // the usual log4j levels, minus FAIL (we just throw an Error in that case)
85     public static final int DEBUG = 0;
86     public static final int INFO = 1;
87     public static final int WARN = 2;
88     public static final int ERROR = 3;
89     public static final int SILENT = Integer.MAX_VALUE;
90     public static int level = INFO;
91
92     private static final int BLUE = 34;
93     private static final int GREEN = 32;
94     private static final int CYAN = 36;
95     private static final int RED = 31;
96     private static final int PURPLE = 35;
97     private static final int BROWN = 33;
98     private static final int GRAY = 37;
99     
100     private static String colorize(int color, boolean bright, String s) {
101         if (!Log.color) return s;
102         return
103             "\033[40;" + (bright?"1;":"") + color + "m" +
104             s +
105             "\033[0m";
106     }
107
108     private static String lastClassName = null;
109     private static synchronized void log(Object o, Object message, int level) {
110         if (level < Log.level) return;
111         if (firstMessage && !logDates) {
112             firstMessage = false;
113             logstream.println(colorize(GREEN, false, "==========================================================================="));
114
115             // FIXME later: causes problems with method pruning
116             //diag(Log.class, "Logging enabled at " + new java.util.Date());
117
118             if (color) diag(Log.class, "logging messages in " +
119                 colorize(BLUE, true, "c") +
120                 colorize(RED, true, "o") +
121                 colorize(CYAN, true, "l") +
122                 colorize(GREEN, true, "o") +
123                 colorize(PURPLE, true, "r"));
124         }
125
126         String classname;
127         if (o instanceof Class) {
128             classname = ((Class)o).getName();
129             if (classname.indexOf('.') != -1) classname = classname.substring(classname.lastIndexOf('.') + 1);
130         }
131         else if (o instanceof String) classname = (String)o;
132         else classname = o.getClass().getName();
133
134         if (classname.equals(lastClassName)) classname = "";
135         else lastClassName = classname;
136         
137         if (classname.length() > (logDates ? 14 : 20)) classname = classname.substring(0, (logDates ? 14 : 20));
138         while (classname.length() < (logDates ? 14 : 20)) classname = " " + classname;
139         classname = classname + (classname.trim().length() == 0 ? "  " : ": ");
140         classname = colorize(GRAY, true, classname);
141         classname = classname.replace('$', '.');
142
143         if (logDates) {
144             Date d = new Date();
145             if (lastDate == null || d.getYear() != lastDate.getYear() || d.getMonth() != lastDate.getMonth() || d.getDay() != lastDate.getDay()) {
146                 String now = new java.text.SimpleDateFormat("EEE dd MMM yyyy").format(d);
147                 logstream.println();
148                 logstream.println(colorize(GRAY, false, "=== " + now + " =========================================================="));
149             }
150             java.text.DateFormat df = new java.text.SimpleDateFormat("[EEE HH:mm:ss] ");
151             classname = df.format(d) + classname;
152             lastDate = d;
153         }
154
155         String annot = (String)threadAnnotations.get(Thread.currentThread());
156         if (annot != null) classname += annot;
157
158         if (message instanceof Throwable) {
159             if (level < ERROR) level = WARN;
160             ByteArrayOutputStream baos = new ByteArrayOutputStream();
161             ((Throwable)message).printStackTrace(new PrintStream(baos));
162             if (notes && notebuf().length() > 0) {
163                 PrintWriter pw = new PrintWriter(baos);
164                 pw.println();
165                 pw.println("Thread notes:");
166                 pw.println(notebuf().toString());
167                 clearnotes();
168                 pw.flush();
169             }
170             byte[] b = baos.toByteArray();
171             BufferedReader br = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(b)));
172             String s = null;
173             try {
174                 String m = "";
175                 while((s = br.readLine()) != null) m += s + "\n";
176                 if (m.length() > 0) log(o, m.substring(0, m.length() - 1), level);
177             } catch (IOException e) {
178                 // FEATURE: use org.ibex.io.Stream's here
179                 logstream.println(colorize(RED, true, "Logger: exception thrown by ByteArrayInputStream; this should not happen"));
180             }
181             lastClassName = "";
182             return;
183         }
184
185         String str = message.toString();
186         if (str.indexOf('\n') != -1) lastClassName = "";
187         while(str.indexOf('\t') != -1)
188             str = str.substring(0, str.indexOf('\t')) + "    " + str.substring(str.indexOf('\t') + 1);
189
190         classname = colorize(GRAY, false, classname);
191         int levelcolor = GRAY;
192         boolean bright = true;
193         switch (level) {
194             case DIAGNOSTIC:  levelcolor = GREEN; bright = false; break;
195             case ECHO:        levelcolor = BLUE;  bright = true;  break;
196             case DEBUG:       levelcolor = BROWN; bright = true;  break;
197             case INFO:        levelcolor = GRAY;  bright = false; break;
198             case WARN:        levelcolor = BROWN; bright = false; break;
199             case ERROR:       levelcolor = RED;   bright = true;  break;
200         }
201
202         while(str.indexOf('\n') != -1) {
203             logstream.println(classname + colorize(levelcolor, bright, str.substring(0, str.indexOf('\n'))));
204             classname = logDates ? "                " : "                      ";
205             classname = colorize(GRAY,false,classname);
206             str = str.substring(str.indexOf('\n') + 1);
207         }
208         logstream.println(classname + colorize(levelcolor, bright, str));
209     }
210
211     // FIXME: Update for new api
212     /*public static void recursiveLog(String indent, String name, Object o) throws JSExn {
213         if (!name.equals("")) name += " : ";
214
215         if (o == null) {
216             JS.log(indent + name + "<null>");
217
218         } else if (o instanceof JSArray) {
219             JS.log(indent + name + "<array>");
220             JSArray na = (JSArray)o;
221             for(int i=0; i<na.length(); i++)
222                 recursiveLog(indent + "  ", i + "", na.elementAt(i));
223
224         } else if (o instanceof JS) {
225             JS.log(indent + name + "<object>");
226             JS s = (JS)o;
227             Enumeration e = s.keys();
228             while(e.hasMoreElements()) {
229                 Object key = e.nextElement();
230                 if (key != null)
231                     recursiveLog(indent + "  ", key.toString(),
232                                  (key instanceof Integer) ?
233                                  s.get(((Integer)key)) : s.get(key.toString()));
234             }
235         } else {
236             JS.log(indent + name + o);
237
238         }
239     }*/
240
241 }