1 33 34 package edu.rice.cs.util; 35 36 import java.io.*; 37 38 import java.util.Arrays ; 39 import java.util.Date ; 40 41 45 public class Log { 46 public static final boolean ENABLE_ALL = false; 47 48 49 protected volatile boolean _isEnabled; 50 51 52 protected volatile String _name; 53 54 55 protected volatile File _file; 56 57 58 protected volatile PrintWriter _writer; 59 60 65 public Log(String name, boolean isEnabled) { this(new File(name), isEnabled); } 66 67 public Log(File f, boolean isEnabled) { 68 _file = f; 69 _name = f.getName(); 70 _isEnabled = isEnabled; 71 _init(); 72 } 73 74 75 protected void _init() { 76 if (_writer == null) { 77 if (_isEnabled || ENABLE_ALL) { 78 try { 79 FileWriter w = new FileWriter(_file.getAbsolutePath(), true); 80 _writer = new PrintWriter(w); 81 82 log("Log '" + _name + "' opened: " + (new Date ())); 83 } 84 catch (IOException ioe) { 85 throw new RuntimeException ("Could not create log: " + ioe); 86 } 87 } 88 } 89 } 90 91 94 public void setEnabled(boolean isEnabled) { _isEnabled = isEnabled; } 95 96 97 public boolean isEnabled() { return (_isEnabled || ENABLE_ALL); } 98 99 102 public synchronized void log(String message) { 103 if (isEnabled()) { 104 if (_writer == null) { 105 _init(); 106 } 107 _writer.println((new Date ()) + ": " + message); 108 _writer.flush(); 109 } 110 } 111 112 113 public static String traceToString(StackTraceElement [] trace) { 114 final StringBuilder traceImage = new StringBuilder (); 115 for (StackTraceElement e: trace) traceImage.append("\n" + e.toString()); 116 return traceImage.toString(); 117 } 118 119 123 public synchronized void log(String s, StackTraceElement [] trace) { 124 if (isEnabled()) log(s + traceToString(trace)); 125 } 126 127 131 public synchronized void log(String s, Throwable t) { 132 if (isEnabled()) { 133 StringWriter sw = new StringWriter(); 134 PrintWriter pw = new PrintWriter(sw); 135 t.printStackTrace(pw); 136 log(s + "\n" + sw.toString()); 137 } 138 } 139 } | Popular Tags |