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?
Asked
Active
Viewed 1.7k times
13

davioooh
- 23,742
- 39
- 159
- 250
-
Can you make it part of the message itself? – mazaneicha Jul 16 '12 at 14:02
-
See also: [Spring: Standard Logging aspect (interceptor)](http://stackoverflow.com/questions/7302090) – Tomasz Nurkiewicz Jul 16 '12 at 16:18
3 Answers
16
@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;
}

atrain
- 9,139
- 1
- 36
- 40
-
This even works for proxied classes (the non-proxied name is shown in the log message). – jolo Sep 06 '17 at 14:49
13
this is easier:
pjp.getTarget().getClass()

Ivan Velykorodnyy
- 401
- 3
- 11
-
1But one problem ProceedingJoinPoint is only supported for around advice only not for Before or After – Tayab Hussain Apr 07 '17 at 13:59
4
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());

Nitul
- 997
- 12
- 35
-
This is not a good practice i.e. asking for logger object for every advice method call. – Mohit May 21 '20 at 12:21
-
1Good point @Mohit, but Slf4J has an implementation of having all the logger objects cached, so it's not a significant overhead. – varra Jan 11 '23 at 12:58