RollingDateFileHandler.java :  » Development » jLo » org » jzonic » jlo » handler » Java Open Source

Java Open Source » Development » jLo 
jLo » org » jzonic » jlo » handler » RollingDateFileHandler.java
package org.jzonic.jlo.handler;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import org.jzonic.jlo.LogRecord;
import org.jzonic.jlo.error.ErrorHandler;

// Referenced classes of package org.jlo.handler:
//            Handler

public class RollingDateFileHandler extends AbstractHandler {

  private String fileName;
  private int maxSize;
  private String dateFormat;

  /**
   * 
   */
  public RollingDateFileHandler(String configName) {
    super(configName);
    fileName = null;
    maxSize = -1;
    dateFormat = "dd.MM.yyyy";
  }

  /**
   * 
   * @param msg 
   */
  public void publish(String msg) {
      String fn = prepareFileName();
    if (fileName == null )
      ErrorHandler.reportError("No filename specified");
    try {        
      File file = new File(fn);
          boolean append = true;
          if ( file.exists() && maxSize != -1 ) {
            long length = file.length();
            if ( length > maxSize*1024 ) {
              append = false;
            }
          }
            FileWriter fw = new FileWriter(fn, append);
      fw.write(msg + "\n");
      fw.close();
    } catch (Exception e) {
      ErrorHandler.reportError(
        "Exception while trying to write to file: " + fn,
        e);
    }
  }

  /**
   * 
   * @param lr 
   */
  public void publish(LogRecord lr) {
    publish(lr.getMessage());
  }

  /**
   * Sets the parameters. The required parameters are:<br/>
         *
   * @param parameters 
   */       
  public void setParameter(Map parameters) {
    if (parameters.containsKey("file"))
      fileName = (String) parameters.get("file");
    if (parameters.containsKey("maxsize"))
      maxSize = Integer.parseInt((String) parameters.get("maxsize"));
    if (parameters.containsKey("format"))
      dateFormat = (String) parameters.get("format");
  }

  private String prepareFileName() {
    if (fileName != null) {
      String tmpName = fileName.toLowerCase();
      int pos = tmpName.indexOf("${date}");
      if (pos == -1) {
        return fileName;
      } else {
        Date rightNow = new Date(System.currentTimeMillis());
        String firstPart = fileName.substring(0, pos - 1);
        String secondPart = fileName.substring(pos + 7);
        SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
        String dateString = formatter.format(rightNow);
        return firstPart + dateString + secondPart;
      }
    } else {
      return null;
    }
  }

}
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.