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