一般写log4j,每个类都会定义一个logger
明显这样太麻烦了,
然后封装了一下,明显好用多了。
1 package tools; 2 3 import java.io.IOException; 4 import java.io.InputStream; 5 import java.util.Properties; 6 7 import org.apache.log4j.Level; 8 import org.apache.log4j.Logger; 9 10 public class LogUtil { 11 private static final String LOG4J_PROPERITES_PATH = "log4j.properties"; 12 13 public static void debug(Object str_debug) { 14 StackTraceElement stack[] = (new Throwable()).getStackTrace(); 15 16 Logger logger = Logger.getLogger(stack[1].getClassName()); 17 logger.log(LogUtil.class.getName(), Level.DEBUG, str_debug, null); 18 //logger.debug(str_debug); 19 } 20 21 public static void info(Object str_info) { 22 StackTraceElement stack[] = (new Throwable()).getStackTrace(); 23 24 Logger logger = Logger.getLogger(stack[1].getClassName()); 25 logger.log(LogUtil.class.getName(), Level.INFO, str_info, null); 26 //logger.info(str_info); 27 } 28 29 public static void error(Object str_err) { 30 StackTraceElement stack[] = (new Throwable()).getStackTrace(); 31 32 Logger logger = Logger.getLogger(stack[1].getClassName()); 33 logger.log(LogUtil.class.getName(), Level.ERROR, str_err, null); 34 //logger.error(str_err); 35 } 36 37 @SuppressWarnings("unused") 38 private static void logClean(String... clean_types) { 39 if (clean_types.length == 0) { 40 return ; 41 } 42 InputStream in = ClassLoader.getSystemResourceAsStream(LOG4J_PROPERITES_PATH); 43 Properties p = new Properties(); 44 try { 45 p.load(in); 46 } catch (IOException e) { 47 error("Properties 加载错误"); 48 } 49 50 for (int i = 0; i < clean_types.length; i++) { 51 String clean_type = clean_types[i]; 52 String file_path = null; 53 switch(clean_type) { 54 case "debug" : 55 file_path = p.getProperty("log4j.appender.D.File"); 56 break; 57 case "info" : 58 file_path = p.getProperty("log4j.appender.info.File"); 59 break; 60 case "error" : 61 file_path = p.getProperty("log4j.appender.E.File"); 62 break; 63 } 64 FileUtil.deleteEveryThing(file_path); 65 } 66 } 67 68 public static void main(String[] args) { 69 //logClean("debug", "info", "error"); 70 } 71 72 }