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