1 package org.jzonic.jlo.handler; 2 3 import org.jzonic.jlo.LogRecord; 4 import org.jzonic.jlo.VariableManager; 5 import org.jzonic.jlo.error.ErrorHandler; 6 7 import java.io.File ; 8 import java.io.FileWriter ; 9 import java.text.SimpleDateFormat ; 10 import java.util.Date ; 11 import java.util.Map ; 12 13 16 public class DateFileHandler extends AbstractHandler { 17 18 private static final VariableManager vm = VariableManager.getInstance(); 19 private String fileName; 20 private int maxSize; 21 private String dateFormat; 22 23 public DateFileHandler(String configName) { 24 super(configName); 25 fileName = null; 26 maxSize = -1; 27 dateFormat = "dd.MM.yyyy"; 28 } 29 30 public void publish(String msg) { 31 String fn = prepareFileName(); 32 if (fileName == null) 33 ErrorHandler.reportError("No filename specified"); 34 try { 35 File file = new File (fn); 36 boolean append = true; 37 if ( file.exists() && maxSize != -1 ) { 38 long length = file.length(); 39 if ( length > maxSize*1024 ) { 40 append = false; 41 } 42 } 43 FileWriter fw = new FileWriter (fn, append); 44 fw.write(msg + "\n"); 45 fw.close(); 46 } catch (Exception e) { 47 ErrorHandler.reportError("Exception while trying to write to file: " + fn,e); 48 } 49 } 50 51 public void publish(LogRecord lr) { 52 publish(lr.getMessage()); 53 } 54 55 public void setParameter(Map parameters) { 56 if (parameters.containsKey("file")) 57 fileName = (String ) parameters.get("file"); 58 if (parameters.containsKey("maxsize")) 59 maxSize = Integer.parseInt((String ) parameters.get("maxsize")); 60 if (parameters.containsKey("format")) 61 dateFormat = (String ) parameters.get("format"); 62 } 63 64 public String prepareFileName() { 65 if (fileName != null) { 66 String fn = null; 67 String tmpName = fileName.toLowerCase(); 68 int pos = tmpName.indexOf("${date}"); 69 if (pos == -1) { 70 fn = fileName; 71 } else { 72 Date rightNow = new Date (System.currentTimeMillis()); 73 String firstPart = fileName.substring(0, pos ); 74 String secondPart = fileName.substring(pos + 7); 75 SimpleDateFormat formatter = new SimpleDateFormat (dateFormat); 76 String dateString = formatter.format(rightNow); 77 fn = firstPart + dateString + secondPart; 78 } 79 return vm.replaceVariables(fn, getConfigurationName()); 80 } else { 81 return null; 82 } 83 } 84 85 } | Popular Tags |