Here's a simple class I use in my LWJGL games to log info and exceptions. I also wrote a
blog post about it explaining this class. Suggestions are welcome. Features:
- A simple, easy to maintain piece of code, no dependencies.
- Write info, warning, or error messages along with the exact time of occurrence.
- Write the full stack trace when an exception occurs.
- Logfile rotating: avoid filling op storage space by limiting maximum logfile size. A backup will be made of the current log when the size is reached, and this backup will be overwritten by the next backup.
Be sure to initialize at startup.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
| import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Date;
public class Logging {
static File file; static long maxSize; static SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
public static void initialize(String fileName, long maxSizeKb) { if (file != null) { throw new RuntimeException("Logging already initialized"); } file = new File(fileName); Logging.maxSize = maxSizeKb * 1024; }
public static void error(String message) { write("ERROR", message); }
public static void error(String message, Throwable t) { write("ERROR", message, t); }
public static void warning(String message) { write("WARNING", message); }
public static void info(String message) { write("INFO", message); }
private static void write(String prefix, String message) { checkRotate(); try (BufferedWriter bw = new BufferedWriter(new FileWriter(file, true))) { bw.write("[" + prefix + " " + format.format(new Date()) + "] " + message + "\n"); } catch (IOException ioe) { ioe.printStackTrace(); } }
private static void write(String prefix, String message, Throwable t) { checkRotate(); try (BufferedWriter bw = new BufferedWriter(new FileWriter(file, true))) { bw.write("[" + prefix + " " + format.format(new Date()) + "] " + message + ":\n"); t.printStackTrace(new PrintWriter(bw)); } catch (IOException ioe) { ioe.printStackTrace(); } t.printStackTrace(); }
private static void checkRotate() { try { if (file.length() >= maxSize) { File secondFile = new File(file.getName() + ".old"); if (secondFile.exists()) { secondFile.delete(); } file.renameTo(secondFile); } } catch (Exception ioe) { ioe.printStackTrace(); } } } |