1 19 20 package org.netbeans.modules.projectimport.j2seimport; 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 Level LEVEL = Level.INFO; 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 static { 55 String levelName = System.getProperty("projectimport.logging.level"); if (levelName != null) { 57 try { 58 LEVEL = Level.parse(levelName); 59 } catch (IllegalArgumentException iae) { 60 } 62 } 63 } 64 65 68 public Logger createLogger(Class clazz) { 69 Logger logger = Logger.getLogger(clazz.getName()); 70 ConsoleHandler ch = new ConsoleHandler (); 71 ch.setLevel(LEVEL); 72 ch.setFormatter(new BasicFormatter()); 73 logger.addHandler(ch); 74 logger.setUseParentHandlers(false); 75 logger.setLevel(LEVEL); 76 return logger; 77 } 78 79 80 private static class BasicFormatter extends Formatter { 81 private Date dat = new Date (); 82 private final static String format = "yyyyMMdd_HHmmss z"; private DateFormat formatter = new SimpleDateFormat (format); 84 85 public String format(LogRecord record) { 86 StringBuffer sb = new StringBuffer (); 87 String name = record.getLevel().getName(); 88 for (int i = name.length(); i < MAX_LEVEL_LENGTH; i++) { 90 sb.append(" "); } 92 sb.append("[" + name + "]: "); dat.setTime(record.getMillis()); 96 sb.append(formatter.format(dat)); 97 sb.append(" - "); if (record.getSourceClassName() != null) { 100 sb.append(record.getSourceClassName()); 101 } else { 102 sb.append(record.getLoggerName()); 103 } 104 if (record.getSourceMethodName() != null) { 105 sb.append("."); sb.append(record.getSourceMethodName()); 107 sb.append("()"); } 109 sb.append(": "); sb.append(record.getMessage()); 112 if (record.getThrown() != null) { 113 try { 114 sb.append("\n "); StringWriter sw = new StringWriter (); 116 PrintWriter pw = new PrintWriter (sw); 117 record.getThrown().printStackTrace(pw); 118 pw.close(); 119 sb.append(sw.toString()); 120 } catch (Exception ex) { 121 } 122 } else { 123 sb.append("\n"); } 125 return sb.toString(); 126 } 127 } 128 129 } 130 | Popular Tags |