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