01: // Copyright (C) 2003,2004,2005 by Object Mentor, Inc. All rights reserved.
02: // Released under the terms of the GNU General Public License version 2 or later.
03:
04: package fitnesse.components;
05:
06: import java.io.*;
07: import java.text.*;
08: import java.util.*;
09:
10: public class Logger {
11: private File directory;
12:
13: public static SimpleDateFormat makeLogFormat() {
14: // SimpleDateFormat is not thread safe, so we need to create each
15: // instance independently.
16: return new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss Z");
17: }
18:
19: public static SimpleDateFormat makeFileNameFormat() {
20: // SimpleDateFormat is not thread safe, so we need to create each
21: // instance independently.
22: return new SimpleDateFormat("yyyyMMddHHmmss");
23: }
24:
25: private PrintWriter writer;
26:
27: private GregorianCalendar currentFileCreationDate;
28:
29: public Logger(String dirPath) {
30: directory = new File(dirPath);
31: directory.mkdir();
32: }
33:
34: public File getDirectory() {
35: return directory;
36: }
37:
38: String formatLogLine(LogData data) {
39: StringBuffer line = new StringBuffer();
40: line.append(data.host).append(" - - [");
41: line.append(format(makeLogFormat(), data.time)).append("] ");
42: line.append('"').append(data.requestLine).append("\" ");
43: line.append(data.status).append(" ");
44: line.append(data.size);
45: return line.toString();
46: }
47:
48: static String makeLogFileName(Calendar calendar) {
49: StringBuffer name = new StringBuffer();
50: name.append("fitnesse").append(
51: format(makeFileNameFormat(), calendar)).append(".log");
52: return name.toString();
53: }
54:
55: public void log(LogData data) throws Exception {
56: if (needNewFile(data.time))
57: openNewFile(data);
58: writer.println(formatLogLine(data));
59: writer.flush();
60: }
61:
62: private boolean needNewFile(GregorianCalendar time) {
63: if (writer == null)
64: return true;
65: else {
66: boolean different = (time.get(Calendar.DAY_OF_YEAR) != currentFileCreationDate
67: .get(Calendar.DAY_OF_YEAR))
68: || (time.get(Calendar.YEAR) != currentFileCreationDate
69: .get(Calendar.YEAR));
70: return different;
71: }
72:
73: }
74:
75: private void openNewFile(LogData data) throws FileNotFoundException {
76: if (writer != null)
77: writer.close();
78: currentFileCreationDate = data.time;
79: String filename = makeLogFileName(data.time);
80: File file = new File(directory, filename);
81: FileOutputStream outputStream = new FileOutputStream(file);
82: writer = new PrintWriter(outputStream);
83: }
84:
85: public void close() {
86: if (writer != null)
87: writer.close();
88: }
89:
90: private static String format(DateFormat format, Calendar calendar) {
91: DateFormat tmpFormat = (DateFormat) format.clone();
92: tmpFormat.setTimeZone(calendar.getTimeZone());
93: return tmpFormat.format(calendar.getTime());
94: }
95:
96: public String toString() {
97: return getDirectory().getAbsolutePath();
98: }
99: }
|