001: package org.jzonic.jlo.handler;
002:
003: import java.io.*;
004: import java.text.SimpleDateFormat;
005: import java.util.Date;
006: import java.util.Map;
007:
008: import org.jzonic.jlo.LogRecord;
009: import org.jzonic.jlo.error.ErrorHandler;
010:
011: // Referenced classes of package org.jlo.handler:
012: // Handler
013:
014: public class RollingDateFileHandler extends AbstractHandler {
015:
016: private String fileName;
017: private int maxSize;
018: private String dateFormat;
019:
020: /**
021: *
022: */
023: public RollingDateFileHandler(String configName) {
024: super (configName);
025: fileName = null;
026: maxSize = -1;
027: dateFormat = "dd.MM.yyyy";
028: }
029:
030: /**
031: *
032: * @param msg
033: */
034: public void publish(String msg) {
035: String fn = prepareFileName();
036: if (fileName == null)
037: ErrorHandler.reportError("No filename specified");
038: try {
039: File file = new File(fn);
040: boolean append = true;
041: if (file.exists() && maxSize != -1) {
042: long length = file.length();
043: if (length > maxSize * 1024) {
044: append = false;
045: }
046: }
047: FileWriter fw = new FileWriter(fn, append);
048: fw.write(msg + "\n");
049: fw.close();
050: } catch (Exception e) {
051: ErrorHandler
052: .reportError(
053: "Exception while trying to write to file: "
054: + fn, e);
055: }
056: }
057:
058: /**
059: *
060: * @param lr
061: */
062: public void publish(LogRecord lr) {
063: publish(lr.getMessage());
064: }
065:
066: /**
067: * Sets the parameters. The required parameters are:<br/>
068: *
069: * @param parameters
070: */
071: public void setParameter(Map parameters) {
072: if (parameters.containsKey("file"))
073: fileName = (String) parameters.get("file");
074: if (parameters.containsKey("maxsize"))
075: maxSize = Integer.parseInt((String) parameters
076: .get("maxsize"));
077: if (parameters.containsKey("format"))
078: dateFormat = (String) parameters.get("format");
079: }
080:
081: private String prepareFileName() {
082: if (fileName != null) {
083: String tmpName = fileName.toLowerCase();
084: int pos = tmpName.indexOf("${date}");
085: if (pos == -1) {
086: return fileName;
087: } else {
088: Date rightNow = new Date(System.currentTimeMillis());
089: String firstPart = fileName.substring(0, pos - 1);
090: String secondPart = fileName.substring(pos + 7);
091: SimpleDateFormat formatter = new SimpleDateFormat(
092: dateFormat);
093: String dateString = formatter.format(rightNow);
094: return firstPart + dateString + secondPart;
095: }
096: } else {
097: return null;
098: }
099: }
100:
101: }
|