1 package com.protomatter.syslog; 2 3 52 53 import java.io.*; 54 import java.net.*; 55 import java.util.*; 56 import java.util.zip.*; 57 import java.text.*; 58 59 import com.protomatter.util.*; 60 61 66 public class FileLog 67 extends BasicLogger 68 { 69 private boolean append = true; 70 71 private File file; 72 private Writer out = null; 73 private boolean autoFlush = true; 74 75 78 public FileLog(File f) 79 { 80 this(f, true, false); 81 } 82 83 86 public FileLog(File f, boolean append, boolean autoFlush) 87 { 88 this(); 89 setFile(f); 90 setAppend(append); 91 setAutoFlush(autoFlush); 92 } 93 94 97 public FileLog() 98 { 99 super(); 100 } 101 102 105 public synchronized void setFile(File f) 106 { 107 cleanup(); 108 file = f; 109 } 110 111 114 public File getFile() 115 { 116 return this.file; 117 } 118 119 122 public void setAppend(boolean append) 123 { 124 this.append = append; 125 } 126 127 130 public boolean getAppend() 131 { 132 return this.append; 133 } 134 135 138 public void setAutoFlush(boolean flush) 139 { 140 this.autoFlush = flush; 141 } 142 143 146 public boolean getAutoFlush() 147 { 148 return this.autoFlush; 149 } 150 151 154 public final void log(SyslogMessage message) 155 { 156 StringBuffer b = null; 157 if (message.detail == null) 158 b = new StringBuffer (128); 159 else 160 b = new StringBuffer (256); 161 formatLogEntry(b, message); 162 163 try 164 { 165 if (out == null) 166 { 167 synchronized(file) 168 { 169 if (out == null) 170 { 171 out = new BufferedWriter( 172 new FileWriter(file.getCanonicalPath(), append)); 173 out.write(formatter.getLogHeader()); 174 } 175 } 176 } 177 out.write(b.toString()); 178 if (autoFlush) 179 out.flush(); 180 } 181 catch (IOException x) 182 { 183 System.err.println(MessageFormat.format( 184 Syslog.getResourceString(MessageConstants.FILELOG_CANNOT_WRITE_MESSAGE), 185 new Object [] { x.toString() })); 186 x.printStackTrace(); 187 } 188 } 189 190 private void cleanup() 191 { 192 if (out != null) 193 { 194 try 195 { 196 out.write(formatter.getLogFooter()); 197 out.flush(); 198 out.close(); 199 out = null; 200 } 201 catch (IOException x) 202 { 203 x.printStackTrace(); 204 } 205 } 206 } 207 208 211 public synchronized void shutdown() 212 { 213 cleanup(); 214 } 215 216 public void flush() 217 { 218 try 219 { 220 if (out != null) 221 out.flush(); 222 } 223 catch (IOException x) 224 { 225 x.printStackTrace(); 226 } 227 } 228 } 229 | Popular Tags |