1 2 3 4 package net.nutch.util; 5 6 import java.util.logging.*; 7 import java.io.*; 8 import java.text.*; 9 import java.util.Date ; 10 11 12 13 public class LogFormatter extends Formatter { 14 private static final String FORMAT = "yyMMdd HHmmss"; 15 private static final String NEWLINE = System.getProperty("line.separator"); 16 17 private final Date date = new Date (); 18 private final SimpleDateFormat formatter = new SimpleDateFormat(FORMAT); 19 20 private static boolean loggedSevere= false; 21 22 private static boolean showThreadIDs = false; 23 24 static { 26 Handler[] handlers = LogFormatter.getLogger("").getHandlers(); 27 for (int i = 0; i < handlers.length; i++) { 28 handlers[i].setFormatter(new LogFormatter()); 29 handlers[i].setLevel(Level.FINEST); 30 } 31 } 32 33 35 public static Logger getLogger(String name) { 36 return Logger.getLogger(name); 38 } 39 40 41 public static void setShowThreadIDs(boolean showThreadIDs) { 42 LogFormatter.showThreadIDs = showThreadIDs; 43 } 44 45 50 public synchronized String format(LogRecord record) { 51 StringBuffer buffer = new StringBuffer (); 52 53 date.setTime(record.getMillis()); 55 formatter.format(date, buffer, new FieldPosition(0)); 56 57 if (showThreadIDs) { 59 buffer.append(" "); 60 buffer.append(record.getThreadID()); 61 } 62 63 if (record.getLevel() == Level.SEVERE) { 65 buffer.append(" SEVERE"); loggedSevere= true; } 68 69 buffer.append(" "); 71 buffer.append(formatMessage(record)); 72 73 buffer.append(NEWLINE); 74 75 if (record.getThrown() != null) { 76 try { 77 StringWriter sw = new StringWriter(); 78 PrintWriter pw = new PrintWriter(sw); 79 record.getThrown().printStackTrace(pw); 80 pw.close(); 81 buffer.append(sw.toString()); 82 } catch (Exception ex) { 83 } 84 } 85 return buffer.toString(); 86 } 87 88 92 public static boolean hasLoggedSevere() { 93 return loggedSevere; 94 } 95 96 97 public static PrintStream getLogStream(final Logger logger, 98 final Level level) { 99 return new PrintStream(new ByteArrayOutputStream() { 100 private int scan = 0; 101 102 private boolean hasNewline() { 103 for (; scan < count; scan++) { 104 if (buf[scan] == '\n') 105 return true; 106 } 107 return false; 108 } 109 110 public void flush() throws IOException { 111 if (!hasNewline()) 112 return; 113 logger.log(level, toString().trim()); 114 reset(); 115 scan = 0; 116 } 117 }, true); 118 } 119 } 120 | Popular Tags |