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