1 19 20 package org.netbeans.modules.projectimport; 21 22 import java.io.PrintWriter ; 23 import java.io.StringWriter ; 24 import java.text.DateFormat ; 25 import java.text.SimpleDateFormat ; 26 import java.util.Date ; 27 import java.util.logging.ConsoleHandler ; 28 import java.util.logging.Formatter ; 29 import java.util.logging.Level ; 30 import java.util.logging.LogRecord ; 31 import java.util.logging.Logger ; 32 33 38 public class LoggerFactory { 39 40 private static LoggerFactory factory = new LoggerFactory(); 41 42 private static final Level LEVEL = readLevel(); 45 46 private static final int MAX_LEVEL_LENGTH = Level.WARNING.getName().length(); 48 49 50 public static LoggerFactory getDefault() { 51 return factory; 52 } 53 54 private static Level readLevel() { 55 Level level = Level.INFO; 56 String levelName = System.getProperty("projectimport.logging.level"); if (levelName != null) { 58 try { 59 level = Level.parse(levelName); 60 } catch (IllegalArgumentException iae) { 61 System.err.println("Unable to parse \"projectimport.logging.level\": " + levelName); } 64 } 65 return level; 66 } 67 68 71 public Logger createLogger(Class clazz) { 72 Logger logger = Logger.getLogger(clazz.getName()); 73 ConsoleHandler ch = new ConsoleHandler (); 74 ch.setLevel(LEVEL); 75 ch.setFormatter(new BasicFormatter()); 76 logger.addHandler(ch); 77 logger.setUseParentHandlers(false); 78 logger.setLevel(LEVEL); 79 return logger; 80 } 81 82 private static class BasicFormatter extends Formatter { 83 84 private final Date dat = new Date (); 85 private final DateFormat formatter = new SimpleDateFormat ("yyyyMMdd_HHmmss z"); 87 public String format(LogRecord record) { 88 StringBuffer sb = new StringBuffer (); 89 String name = record.getLevel().getName(); 90 for (int i = name.length(); i < MAX_LEVEL_LENGTH; i++) { 92 sb.append(' '); 93 } 94 sb.append('[' + name + "]: "); dat.setTime(record.getMillis()); 98 sb.append(formatter.format(dat)); 99 sb.append(" - "); if (record.getSourceClassName() != null) { 102 sb.append(record.getSourceClassName()); 103 } else { 104 sb.append(record.getLoggerName()); 105 } 106 if (record.getSourceMethodName() != null) { 107 sb.append('.'); 108 sb.append(record.getSourceMethodName()); 109 sb.append("()"); } 111 sb.append(": "); sb.append(record.getMessage()); 114 if (record.getThrown() != null) { 115 sb.append("\n "); StringWriter sw = new StringWriter (); 117 PrintWriter pw = new PrintWriter (sw); 118 record.getThrown().printStackTrace(pw); 119 pw.close(); 120 sb.append(sw.toString()); 121 } else { 122 sb.append('\n'); 123 } 124 return sb.toString(); 125 } 126 127 } 128 129 } 130 | Popular Tags |