blob: fd486fbeb4d41a8d234f4310cb28309785cd4741 [file] [log] [blame]
danielp54e997e2013-02-21 01:54:23 +00001/**
2 *
3 */
4package org.frc971;
5
6import java.io.FileOutputStream;
7import java.io.FileNotFoundException;
8import java.io.PrintWriter;
9
10import java.util.logging.Handler;
11import java.util.logging.LogRecord;
12
13/**
14 * @author daniel
danielp64c4e052013-02-23 07:21:41 +000015 *
danielp54e997e2013-02-21 01:54:23 +000016 */
danielp64c4e052013-02-23 07:21:41 +000017
18/** Logs data to custom files, using specific formatting. */
danielp54e997e2013-02-21 01:54:23 +000019public class LogHandler extends Handler {
20
21 private FileOutputStream ofstream;
22 PrintWriter writer;
23
danielp64c4e052013-02-23 07:21:41 +000024 /** Constructor for log handler.
25 *
26 * @param filename is the name of the file you want to log to.
27 * @throws FileNotFoundException if file cannot be opened or created.
28 */
danielp54e997e2013-02-21 01:54:23 +000029 public LogHandler (String filename) throws FileNotFoundException {
30 super();
31
32 if (filename == null || filename == "") {
33 filename = "logfile.log";
34 }
35
36 //check if file exists, and if not, create it
37 ofstream = new FileOutputStream(filename);
38 writer = new PrintWriter(ofstream);
39 setFormatter(new TimeFormatter());
40 }
41
42 /*Required methods*/
43
danielp64c4e052013-02-23 07:21:41 +000044 /** Is required by API. Writes a new message to the log.
45 * @param message is the message you want to log.
46 */
danielp54e997e2013-02-21 01:54:23 +000047 public void publish(LogRecord message) {
48 //record a message
49 if (!isLoggable(message)) {
50 //ensure that this message should be logged by this handler
51 return;
52 }
53 writer.print(getFormatter().format(message)); //Formatter adds trailing \n
54 }
danielp64c4e052013-02-23 07:21:41 +000055
56 /** Is required by API. Flushes the writer. */
danielp54e997e2013-02-21 01:54:23 +000057 public void flush() {
58 writer.flush();
59 }
danielp64c4e052013-02-23 07:21:41 +000060
61 /** Is required by API. Closes logfile. */
danielp54e997e2013-02-21 01:54:23 +000062 public void close() throws SecurityException {
63 writer.close();
64 }
65}