log4j中的通用记录器

时间:2015-09-25 11:00:43

标签: java logging log4j slf4j

我使用泛型类(LoggerUtils.java)来记录代码中的消息。有一个构造函数接受Class作为参数,所有其他类都调用它来初始化一个logger对象。我正在使用slf4j。但我的问题是当我查看日志时,日志会在所有日志中将类名显示为LoggerUtils。我需要从我调用LoggerUtils类的地方看到用于显示日志的类。有没有办法做到这一点?

Log4j.properties:

log4j.appender.SampleLog=org.apache.log4j.DailyRollingFileAppender
log4j.appender.SampleLog.File=/sample.log 
log4j.appender.SampleLog.layout=org.apache.log4j.PatternLayout 
log4j.appender.SampleLog.layout.ConversionPattern=%d{ISO8601} (%c: %M %L) - %m%n 
log4j.category.com.sample=DEBUG, SampleLog 

LoggerUtils.java

    package com.sample.utils;

    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;


    public class LoggerUtils {

        private Logger logger;

        private  LoggerUtils(Class clazz) {
            try {
                logger = LoggerFactory.getLogger(clazz);

            } catch (Exception e) {
                System.out.println("Error in logger");
            }
        }

        public static LoggerUtils getLogger(Class clazz) {
            return new LoggerUtils(clazz);
        }

        public void info(Object message) {
            logger.info(message.toString());
        }
    }


My Sample Class:

    package test;

    import com.sample.utils.LoggerUtils;

    public class Sample{
        LoggerUtils logger = LoggerUtils.getLogger(this.getClass());
        public void print(){
            logger.info("Hello");
        }
    }

在日志中,我得到了:

2015-09-25 16:19:21,784 (test.Sample: info 27) - Hello

我期待的是:

2015-09-25 16:19:21,784 (test.Sample: print 8) - Hello

1 个答案:

答案 0 :(得分:0)

要获取调用实用程序类的方法和行,请获取当前堆栈跟踪并向上移动,直到您离开实用程序类调用的代码:

 StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
 for( StackTraceElement element : stackTrace ) {
    //ignore all entries from within LoggerUtils 
    if( element.getClassName().equalsIgnoreCase( LoggerUtils.class.getName() ) ) {
      continue;
    } else {
      String method = element.getMethodName();
      int lineNo = element.getLineNumber();
      break;
    }
 }