log4j.rootLogger = debug,CONSOLElog4j.appender.CONSOLE = org.apache.log4j.ConsoleAppenderlog4j.appender.Threshold = debuglog4j.appender.CONSOLE.Target = System.outlog4j.appender.CONSOLE.layout = org.apache.log4j.PatternLayoutlog4j.appender.CONSOLE.layout.ConversionPattern =>> %p <> %d{yyyy-MM-dd HH\:mm\:ss}%n>> %m%n%n
其中显示级别一定要选择 debug,因为在静态实现的时候也会设定。
package com.winux;import org.apache.log4j.Logger;public class logs {private static Logger logger = Logger.getLogger(logs.class);private static final String thisClassName = logs.class.getName();//信息分隔符private static final String msgSplit = ":";//是否要定位服务private static boolean showLocSrc = true;//是否显示日志private static final boolean enabled = true;//显示等级private static int level = 1;private static final int debug = 1;private static final int info = 2;private static final int warn = 3;private static final int error = 4;public static final void debug(Object message) {if (!enabled || debug < level)return;if (showLocSrc) {log(debug, message, Thread.currentThread().getStackTrace());} else {log(debug, message, null);}}public static final void info(Object message) {if (!enabled || info < level)return;if (showLocSrc) {log(info, message, Thread.currentThread().getStackTrace());} else {log(info, message, null);}}public static final void warn(Object message) {if (!enabled || warn < level)return;if (showLocSrc) {log(warn, message, Thread.currentThread().getStackTrace());} else {log(warn, message, null);}}public static final void error(Object message) {if (!enabled || error < level)return;if (showLocSrc) {log(error, message, Thread.currentThread().getStackTrace());} else {log(error, message, null);}}private static String getStackMsg(StackTraceElement[] ste) {if (ste == null)return null;boolean srcFlag = false;for (int i = 0; i < ste.length; i++) {StackTraceElement s = ste[i];// 如果上一行堆栈代码是本类的堆栈,则该行代码则为源代码的最原始堆栈。if (srcFlag) {return s == null ? "" : s.toString();}// 定位本类的堆栈if (thisClassName.equals(s.getClassName())) {srcFlag = true;}}return null;}private static void log(int level, Object message, StackTraceElement[] ste) {if (ste != null) {message = getStackMsg(ste) + msgSplit + message;}switch (level) {case info:logger.info(message);break;case debug:logger.debug(message);break;case warn:logger.warn(message);break;case error:logger.error(message);break;default:logger.debug(message);}}public static void main(String[] args) {logs.debug("测试输出");logs.info("测试输出");}}