Log4j and AOP, how to get actual class name

ぃ、小莉子 提交于 2019-12-04 18:30:36

问题


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 LoggerAspect class name, so... is there a way to trace the actual class name in my log?


回答1:


@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;
}



回答2:


this is easier:

pjp.getTarget().getClass()



回答3:


Use : 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());


来源:https://stackoverflow.com/questions/11505735/log4j-and-aop-how-to-get-actual-class-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!