【问题标题】:Printing calling class name in logs using logback使用 logback 在日志中打印调用类名
【发布时间】:2014-04-14 12:09:59
【问题描述】:

我在记录调用类的类名时遇到问题。我有用 logback 编写的日志记录实用程序类。出于某些性能原因,我使用单例模式创建了记录器实用程序。但是当我从其他类调用日志语句时,我会打印实用程序的类名而不是调用类。

private static LogUtil logutil =null;   
    public static LogUtil getInstance(){        
        if(logutil==null){
            logutil = new LogUtil();
        }
        return logutil;

    }
protected static final Logger LOGGER = (Logger)LoggerFactory.getLogger("MyModule");

public void info(String Message){
        if(LOGGER.isInfoEnabled()){
            LOGGER.info(Message);

        }
}

测试类类似于

public class LogUtilTest {
public static void testforlogging(){
logutil.info(“Im Logging this message”);
}
}

我得到如下输出,打印 LogUtil 而不是 LogUtilTest,我需要帮助记录我的调用类名称

2014-04-14 16:47:21 INFO [main] MyModule [LogUtil.info:42] 类名 [com.commonutil.logging.LogUtil] - 方法 [testforlogging] - 没有 个人资料-100001

【问题讨论】:

    标签: java logging log4j logback


    【解决方案1】:

    您可以使用Thread.currentThread().getStackTrace() 访问当前调用堆栈。它返回一个StackTraceElement 数组。第一项始终代表getStackTrace()。第二个是调用它的方法,第三个是你想要的方法

    Thread.currentThread().getStackTrace()[2].getClassName()
    

    返回调用该方法的类的类名。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-27
      • 2021-03-11
      • 2019-04-03
      • 2021-10-28
      • 1970-01-01
      相关资源
      最近更新 更多