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