java Log4j 和 AOP,如何获取实际的类名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11505735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 05:22:21  来源:igfitidea点击:

Log4j and AOP, how to get actual class name

javaspringlog4jspring-aop

提问by davioooh

I'm implementing a logger as an aspect using Spring AOP and Log4J, but I've noticed that the class name in log file is always the LoggerAspectclass name, so... is there a way to trace the actual class name in my log?

我正在使用 Spring AOP 和 Log4J 将记录器作为一个方面来实现,但我注意到日志文件中的LoggerAspect类名始终是类名,所以......有没有办法在我的日志中跟踪实际的类名?

回答by atrain

@Around("execution(* com.mycontrollerpackage.*.*(..))")
public Object aroundWebMethodE(ProceedingJoinPoint pjp) throws Throwable {      
    String packageName = pjp.getSignature().getDeclaringTypeName();
    String methodName = pjp.getSignature().getName();
    long start = System.currentTimeMillis();
    if(!pjp.getSignature().getName().equals("initBinder")) {
       logger.info("Entering method [" + packageName + "." + methodName +  "]");
    }
    Object output = pjp.proceed();
    long elapsedTime = System.currentTimeMillis() - start;
    if(!methodName.equals("initBinder")) {
       logger.info("Exiting method [" + packageName + "." + methodName + "]; exec time (ms): " + elapsedTime);
    }
    return output;
}

回答by Ivan Velykorodnyy

this is easier:

这更容易:

pjp.getTarget().getClass()

回答by Nitul

Use: pjp.getTarget().getClass().getCanonicalName()

使用pjp.getTarget().getClass().getCanonicalName()

Also, to add logs at class level of which method is being exexuted instead using logger of advice class, use class level logger within advice method, as below

此外,要在正在执行的方法的类级别添加日志而不是使用建议类的记录器,请在建议方法中使用类级别记录器,如下所示

Logger logger = Logger.getLogger(pjp.getTarget().getClass().getCanonicalName());