1 25 package org.archive.util; 26 27 import java.io.PrintWriter ; 28 import java.io.StringWriter ; 29 import java.text.FieldPosition ; 30 import java.text.SimpleDateFormat ; 31 import java.util.Date ; 32 import java.util.logging.ConsoleHandler ; 33 import java.util.logging.Handler ; 34 import java.util.logging.Level ; 35 import java.util.logging.LogRecord ; 36 import java.util.logging.Logger ; 37 import java.util.logging.SimpleFormatter ; 38 39 40 41 47 public class OneLineSimpleLogger extends SimpleFormatter { 48 49 54 private Date date = new Date (); 55 56 61 private FieldPosition position = new FieldPosition (0); 62 63 66 private SimpleDateFormat formatter = 67 new SimpleDateFormat ("MM/dd/yyyy HH:mm:ss Z"); 68 69 72 private StringBuffer buffer = new StringBuffer (); 73 74 75 public OneLineSimpleLogger() { 76 super(); 77 } 78 79 public synchronized String format(LogRecord record) { 80 this.buffer.setLength(0); 81 this.date.setTime(record.getMillis()); 82 this.position.setBeginIndex(0); 83 this.formatter.format(this.date, buffer, this.position); 84 buffer.append(' '); 85 buffer.append(record.getLevel().getLocalizedName()); 86 buffer.append(' '); 87 if (record.getSourceClassName() != null) { 88 buffer.append(record.getSourceClassName()); 89 } else { 90 buffer.append(record.getLoggerName()); 91 } 92 buffer.append(' '); 93 String methodName = record.getSourceMethodName(); 94 methodName = (methodName == null || methodName.length() <= 0)? 95 "-": methodName; 96 buffer.append(methodName); 97 buffer.append(' '); 98 buffer.append(formatMessage(record)); 99 buffer.append(System.getProperty("line.separator")); 100 if (record.getThrown() != null) { 101 try { 102 StringWriter writer = new StringWriter (); 103 PrintWriter printer = new PrintWriter (writer); 104 record.getThrown().printStackTrace(printer); 105 writer.close(); 106 buffer.append(writer.toString()); 107 } catch (Exception e) { 108 buffer.append("Failed to get stack trace: " + e.getMessage()); 109 } 110 } 111 return buffer.toString(); 112 } 113 114 public static Logger setConsoleHandler() { 115 Logger logger = Logger.getLogger(""); 116 Handler [] hs = logger.getHandlers(); 117 for (int i = 0; i < hs.length; i++) { 118 Handler h = hs[0]; 119 if (h instanceof ConsoleHandler ) { 120 h.setFormatter(new OneLineSimpleLogger()); 121 } 122 } 123 return logger; 124 } 125 126 129 public static void main(String [] args) { 130 Logger logger = setConsoleHandler(); 131 logger = Logger.getLogger("Test"); 132 logger.severe("Does this come out?"); 133 logger.severe("Does this come out?"); 134 logger.severe("Does this come out?"); 135 logger.log(Level.SEVERE, "hello", new RuntimeException ("test")); 136 } 137 } 138 | Popular Tags |