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