Log.java
1 package hlt; 2 3 import java.io.FileWriter; 4 import java.io.IOException; 5 import java.util.ArrayList; 6 7 public class Log { 8 private final FileWriter file; 9 10 private static Log INSTANCE; 11 private static ArrayList<String> LOG_BUFFER = new ArrayList<>(); 12 13 static { 14 Runtime.getRuntime().addShutdownHook(new AtExit()); 15 } 16 17 private static class AtExit extends Thread { 18 @Override 19 public void run() { 20 if (INSTANCE != null) { 21 return; 22 } 23 24 final long now_in_nanos = System.nanoTime(); 25 final String filename = "bot-unknown-" + now_in_nanos + ".log"; 26 try (final FileWriter writer = new FileWriter(filename)) { 27 for (final String message : LOG_BUFFER) { 28 writer.append(message).append('\n'); 29 } 30 } catch (final IOException e) { 31 // Nothing much we can do here. 32 } 33 } 34 } 35 36 private Log(final FileWriter f) { 37 file = f; 38 } 39 40 static void open(final int botId) { 41 if (INSTANCE != null) { 42 Log.log("Error: log: tried to open(" + botId + ") but we have already opened before."); 43 throw new IllegalStateException(); 44 } 45 46 final String filename = "bot-" + botId + ".log"; 47 final FileWriter writer; 48 try { 49 writer = new FileWriter(filename); 50 } catch (final IOException e) { 51 throw new IllegalStateException(e); 52 } 53 INSTANCE = new Log(writer); 54 55 try { 56 for (final String message : LOG_BUFFER) { 57 writer.append(message).append('\n'); 58 } 59 } catch (final IOException e) { 60 throw new IllegalStateException(e); 61 } 62 LOG_BUFFER.clear(); 63 } 64 65 public static void log(final String message) { 66 if (INSTANCE == null) { 67 LOG_BUFFER.add(message); 68 return; 69 } 70 71 try { 72 INSTANCE.file.append(message).append('\n').flush(); 73 } catch (final IOException e) { 74 e.printStackTrace(); 75 } 76 } 77 }