KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > juli > FileHandler


1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements. See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License. You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */

17
18
19 package org.apache.juli;
20
21 import java.io.File JavaDoc;
22 import java.io.FileWriter JavaDoc;
23 import java.io.PrintWriter JavaDoc;
24 import java.sql.Timestamp JavaDoc;
25 import java.util.logging.ErrorManager JavaDoc;
26 import java.util.logging.Filter JavaDoc;
27 import java.util.logging.Formatter JavaDoc;
28 import java.util.logging.Handler JavaDoc;
29 import java.util.logging.Level JavaDoc;
30 import java.util.logging.LogManager JavaDoc;
31 import java.util.logging.LogRecord JavaDoc;
32 import java.util.logging.SimpleFormatter JavaDoc;
33
34 /**
35  * Implementation of <b>Handler</b> that appends log messages to a file
36  * named {prefix}.{date}.{suffix} in a configured directory, with an
37  * optional preceding timestamp.
38  *
39  * @version $Revision: 467222 $ $Date: 2006-10-24 05:17:11 +0200 (mar., 24 oct. 2006) $
40  */

41
42 public class FileHandler
43     extends Handler JavaDoc {
44
45
46     // ------------------------------------------------------------ Constructor
47

48     
49     public FileHandler() {
50         configure();
51         open();
52     }
53     
54     
55     public FileHandler(String JavaDoc directory, String JavaDoc prefix, String JavaDoc suffix) {
56         this();
57         this.directory = directory;
58         this.prefix = prefix;
59         this.suffix = suffix;
60     }
61     
62
63     // ----------------------------------------------------- Instance Variables
64

65
66     /**
67      * The as-of date for the currently open log file, or a zero-length
68      * string if there is no open log file.
69      */

70     private String JavaDoc date = "";
71
72
73     /**
74      * The directory in which log files are created.
75      */

76     private String JavaDoc directory = null;
77
78
79     /**
80      * The prefix that is added to log file filenames.
81      */

82     private String JavaDoc prefix = null;
83
84
85     /**
86      * The suffix that is added to log file filenames.
87      */

88     private String JavaDoc suffix = null;
89
90
91     /**
92      * The PrintWriter to which we are currently logging, if any.
93      */

94     private PrintWriter JavaDoc writer = null;
95
96
97     // --------------------------------------------------------- Public Methods
98

99
100     /**
101      * Format and publish a <tt>LogRecord</tt>.
102      *
103      * @param record description of the log event
104      */

105     public void publish(LogRecord JavaDoc record) {
106
107         if (!isLoggable(record)) {
108             return;
109         }
110
111         // Construct the timestamp we will use, if requested
112
Timestamp JavaDoc ts = new Timestamp JavaDoc(System.currentTimeMillis());
113         String JavaDoc tsString = ts.toString().substring(0, 19);
114         String JavaDoc tsDate = tsString.substring(0, 10);
115
116         // If the date has changed, switch log files
117
if (!date.equals(tsDate)) {
118             synchronized (this) {
119                 if (!date.equals(tsDate)) {
120                     close();
121                     date = tsDate;
122                     open();
123                 }
124             }
125         }
126
127         String JavaDoc result = null;
128         try {
129             result = getFormatter().format(record);
130         } catch (Exception JavaDoc e) {
131             reportError(null, e, ErrorManager.FORMAT_FAILURE);
132             return;
133         }
134         
135         try {
136             writer.write(result);
137             writer.flush();
138         } catch (Exception JavaDoc e) {
139             reportError(null, e, ErrorManager.WRITE_FAILURE);
140             return;
141         }
142         
143     }
144     
145     
146     // -------------------------------------------------------- Private Methods
147

148
149     /**
150      * Close the currently open log file (if any).
151      */

152     public void close() {
153         
154         try {
155             if (writer == null)
156                 return;
157             writer.write(getFormatter().getTail(this));
158             writer.flush();
159             writer.close();
160             writer = null;
161             date = "";
162         } catch (Exception JavaDoc e) {
163             reportError(null, e, ErrorManager.CLOSE_FAILURE);
164         }
165         
166     }
167
168
169     /**
170      * Flush the writer.
171      */

172     public void flush() {
173
174         try {
175             writer.flush();
176         } catch (Exception JavaDoc e) {
177             reportError(null, e, ErrorManager.FLUSH_FAILURE);
178         }
179         
180     }
181     
182     
183     /**
184      * Configure from <code>LogManager</code> properties.
185      */

186     private void configure() {
187
188         Timestamp JavaDoc ts = new Timestamp JavaDoc(System.currentTimeMillis());
189         String JavaDoc tsString = ts.toString().substring(0, 19);
190         date = tsString.substring(0, 10);
191
192         LogManager JavaDoc manager = LogManager.getLogManager();
193         String JavaDoc className = FileHandler.class.getName();
194         
195         ClassLoader JavaDoc cl = Thread.currentThread().getContextClassLoader();
196         
197         // Retrieve configuration of logging file name
198
directory = getProperty(className + ".directory", "logs");
199         prefix = getProperty(className + ".prefix", "juli.");
200         suffix = getProperty(className + ".suffix", ".log");
201
202         // Get logging level for the handler
203
setLevel(Level.parse(getProperty(className + ".level", "" + Level.ALL)));
204
205         // Get filter configuration
206
String JavaDoc filterName = getProperty(className + ".filter", null);
207         if (filterName != null) {
208             try {
209                 setFilter((Filter JavaDoc) cl.loadClass(filterName).newInstance());
210             } catch (Exception JavaDoc e) {
211                 // Ignore
212
}
213         }
214
215         // Set formatter
216
String JavaDoc formatterName = getProperty(className + ".formatter", null);
217         if (formatterName != null) {
218             try {
219                 setFormatter((Formatter JavaDoc) cl.loadClass(formatterName).newInstance());
220             } catch (Exception JavaDoc e) {
221                 // Ignore
222
}
223         } else {
224             setFormatter(new SimpleFormatter JavaDoc());
225         }
226         
227         // Set error manager
228
setErrorManager(new ErrorManager JavaDoc());
229         
230     }
231
232     
233     private String JavaDoc getProperty(String JavaDoc name, String JavaDoc defaultValue) {
234         String JavaDoc value = LogManager.getLogManager().getProperty(name);
235         if (value == null) {
236             value = defaultValue;
237         } else {
238             value = value.trim();
239         }
240         return value;
241     }
242     
243     
244     /**
245      * Open the new log file for the date specified by <code>date</code>.
246      */

247     private void open() {
248
249         // Create the directory if necessary
250
File JavaDoc dir = new File JavaDoc(directory);
251         dir.mkdirs();
252
253         // Open the current log file
254
try {
255             String JavaDoc pathname = dir.getAbsolutePath() + File.separator +
256                 prefix + date + suffix;
257             writer = new PrintWriter JavaDoc(new FileWriter JavaDoc(pathname, true), true);
258             writer.write(getFormatter().getHead(this));
259         } catch (Exception JavaDoc e) {
260             reportError(null, e, ErrorManager.OPEN_FAILURE);
261             writer = null;
262         }
263
264     }
265
266
267 }
268
Popular Tags