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