compile('log4j:log4j:1.2.17')
logYF.java
package com.demo.test; import org.apache.log4j.Logger; public class logYF { private static Logger logger = Logger.getLogger(logYF.class); public static void info(Object log){ logger.info(appendLogStr(log)); } public static void error(Object log){ logger.error(appendLogStr(log)); } public static void debug(Object log){ logger.debug(appendLogStr(log)); } private static String appendLogStr(Object str) { StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); StackTraceElement log = stackTrace[1]; StringBuffer tag = new StringBuffer(); tag.append("["); for (int i = 1; i < stackTrace.length; i++) { StackTraceElement e = stackTrace[i]; if (!e.getClassName().equals(log.getClassName())) { tag.append(e.getClassName()).append(".").append(e.getMethodName()).append("-").append(e.getLineNumber()); break; } } tag.append("] ").append(str.toString()); return tag.toString(); } }
log4j.properties
### 设置### log4j.rootLogger = debug,stdout,D,E ### 输出信息到控制抬 ### log4j.appender.stdout = org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target = System.out log4j.appender.stdout.layout = org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern = [%p] %d{yyyy-MM-dd HH:mm:ss} %m%n ### 输出DEBUG 级别以上的日志到=log.log ### log4j.appender.D = org.apache.log4j.DailyRollingFileAppender log4j.appender.D.File = C://Data/log.log log4j.appender.D.Append = true log4j.appender.D.Threshold = DEBUG log4j.appender.D.layout = org.apache.log4j.PatternLayout log4j.appender.D.layout.ConversionPattern = [%p] %d{yyyy-MM-dd HH:mm:ss} %m%n ### 输出ERROR 级别以上的日志到=error.log ### log4j.appender.E = org.apache.log4j.DailyRollingFileAppender log4j.appender.E.File =C://Data/error.log log4j.appender.E.Append = true log4j.appender.E.Threshold = ERROR log4j.appender.E.layout = org.apache.log4j.PatternLayout log4j.appender.E.layout.ConversionPattern = [%p] %d{yyyy-MM-dd HH:mm:ss} %m%n
输出结果示例:
[INFO] 2019-06-14 17:28:57 [com.demo.test.TestLog.main-7] aaaaaaaaaaaaaaa [INFO] 2019-06-14 17:28:57 [com.demo.test.TestLog.TestSSS-13] aaaaaaaaaaaaaaa [ERROR] 2019-06-14 17:28:57 [com.demo.test.TestLog.TestSSS-14] ssssss [DEBUG] 2019-06-14 17:28:57 [com.demo.test.TestLog.TestSSS-15] debug