danielp | 54e997e | 2013-02-21 01:54:23 +0000 | [diff] [blame] | 1 | /** |
| 2 | * |
| 3 | */ |
| 4 | package org.frc971; |
| 5 | |
| 6 | import java.io.FileOutputStream; |
| 7 | import java.io.FileNotFoundException; |
| 8 | import java.io.PrintWriter; |
| 9 | |
| 10 | import java.util.logging.Handler; |
| 11 | import java.util.logging.LogRecord; |
| 12 | |
| 13 | /** |
| 14 | * @author daniel |
danielp | 64c4e05 | 2013-02-23 07:21:41 +0000 | [diff] [blame^] | 15 | * |
danielp | 54e997e | 2013-02-21 01:54:23 +0000 | [diff] [blame] | 16 | */ |
danielp | 64c4e05 | 2013-02-23 07:21:41 +0000 | [diff] [blame^] | 17 | |
| 18 | /** Logs data to custom files, using specific formatting. */ |
danielp | 54e997e | 2013-02-21 01:54:23 +0000 | [diff] [blame] | 19 | public class LogHandler extends Handler { |
| 20 | |
| 21 | private FileOutputStream ofstream; |
| 22 | PrintWriter writer; |
| 23 | |
danielp | 64c4e05 | 2013-02-23 07:21:41 +0000 | [diff] [blame^] | 24 | /** 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 | */ |
danielp | 54e997e | 2013-02-21 01:54:23 +0000 | [diff] [blame] | 29 | 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 | |
danielp | 64c4e05 | 2013-02-23 07:21:41 +0000 | [diff] [blame^] | 44 | /** Is required by API. Writes a new message to the log. |
| 45 | * @param message is the message you want to log. |
| 46 | */ |
danielp | 54e997e | 2013-02-21 01:54:23 +0000 | [diff] [blame] | 47 | 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 | } |
danielp | 64c4e05 | 2013-02-23 07:21:41 +0000 | [diff] [blame^] | 55 | |
| 56 | /** Is required by API. Flushes the writer. */ |
danielp | 54e997e | 2013-02-21 01:54:23 +0000 | [diff] [blame] | 57 | public void flush() { |
| 58 | writer.flush(); |
| 59 | } |
danielp | 64c4e05 | 2013-02-23 07:21:41 +0000 | [diff] [blame^] | 60 | |
| 61 | /** Is required by API. Closes logfile. */ |
danielp | 54e997e | 2013-02-21 01:54:23 +0000 | [diff] [blame] | 62 | public void close() throws SecurityException { |
| 63 | writer.close(); |
| 64 | } |
| 65 | } |