1 package snaq.util; 2 3 import java.io.*; 4 import java.text.*; 5 import java.util.*; 6 7 18 public class LogUtil 19 { 20 protected DateFormat dateFormat, ddf; 21 protected PrintStream log; 22 protected boolean logging = false; 23 protected boolean debug = false; 24 25 26 29 public LogUtil() 30 { 31 } 32 33 38 public LogUtil(File f) throws FileNotFoundException 39 { 40 setLog(new FileOutputStream(f, true)); 41 } 42 43 46 public synchronized void setDateFormat(DateFormat df) { dateFormat = df; } 47 48 51 public synchronized void setLog(OutputStream out) 52 { 53 if (log != null) 54 close(); 55 if (out != null) 56 log = new PrintStream(out); 57 logging = true; 58 } 59 60 63 public synchronized void setLog(PrintStream ps) 64 { 65 if (log != null) 66 close(); 67 log = ps; 68 logging = true; 69 } 70 71 74 public PrintStream getLogStream() 75 { 76 return log; 77 } 78 79 82 public synchronized void log(String prefix, String logEntry) 83 { 84 if (!logging) 85 return; 86 StringBuffer sb = new StringBuffer (); 87 if (dateFormat != null) 88 sb.append(dateFormat.format(new Date())); 89 else 90 { 91 if (ddf == null) 92 ddf = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG); 93 sb.append(ddf.format(new Date())); 94 } 95 96 sb.append(": "); 97 if (prefix != null) 98 sb.append(prefix); 99 sb.append(logEntry); 100 if (log != null) 101 { 102 synchronized(log) 103 { 104 log.println(sb.toString()); 105 } 107 } 108 } 109 110 113 public void log(String logEntry) 114 { 115 log("", logEntry); 116 } 117 118 121 public void log(Throwable e, String prefix, String logEntry) 122 { 123 if (!logging) 124 return; 125 log(prefix, logEntry); 126 e.printStackTrace(log); 127 log.flush(); 128 } 129 130 133 public void log(Throwable e, String logEntry) 134 { 135 log(e, "", logEntry); 136 } 137 138 141 public void log(Throwable e) 142 { 143 log(e, e.getMessage()); 144 } 145 146 149 public synchronized void close() 150 { 151 logging = false; 152 if (log != null) 153 { 154 log.flush(); 155 if (!isSystemLog()) 156 log.close(); 157 } 158 log = null; 159 } 160 161 private boolean isSystemLog() 163 { 164 return (!log.equals(System.out) && !log.equals(System.err)); 165 } 166 167 170 public void setLogging(boolean b) { logging = b; } 171 172 175 public boolean isLogging() { return logging; } 176 177 180 public void setDebug(boolean b) { debug = b; } 181 182 185 public boolean isDebug() { return debug; } 186 } | Popular Tags |