Reputation: 2002
I am trying to add log statements before executing every method dynamically using Aspectj.
Code:
@Component
@Aspect
public class MethodLogger {
DiagnosticLogger logger = DiagnosticLogger.getLogger(getClass());
@Before("execution(* com.xyz..*.*(..))")
public void beforeMethod(JoinPoint joinPoint) throws Throwable {
System.out.println("Class******" + joinPoint.getTarget().getClass().getName());
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
System.out.println("Method******" + signature.getName());
// append args
Object[] args = joinPoint.getArgs();
String[] parameterNames = signature.getParameterNames();
if (parameterNames != null) {
for (int i = 0; i < parameterNames.length; i++) {
System.out.println("parameterNames******" + parameterNames[i] + ":" + args[i]);
}
}
}
}
Output:
Class******com.xyz.security.web.UserController
Method******forgotPassword
parameterNames******userEmail:[email protected]
Class******com.xyz.security.service.impl.UserServiceImpl
Method******forgotPassword
parameterNames******userEmail:[email protected]
Class******com.sun.proxy.$Proxy436
Method******findByUserEmail
I am able to get at controller and service level. But when comes to Spring Data JPA Repository method its not able to print. How to get the parameter names at Repository level ?
Upvotes: 1
Views: 724
Reputation: 36143
Here an example of what I did.
By adding + sign also the classes that implement my Repository or any other of my interfaces in com.example.** are intercepted.
@Slf4j
@Component
@Aspect
public class MethodLogger {
@Before("execution(* com.example.*..*+.*(..))")
public void beforeMethod(JoinPoint joinPoint) throws Throwable {
log.info("Class******" + joinPoint.getTarget().getClass().getName());
for (Class<?> theinterface: joinPoint.getTarget().getClass().getInterfaces()) {
log.info("Interfaces******" + theinterface.getName());
}
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
log.info("Method******" + signature.getName());
Object[] args = joinPoint.getArgs();
String[] parameterNames = signature.getParameterNames();
if (parameterNames != null) {
for (int i = 0; i < parameterNames.length; i++) {
log.info("parameterNames******" + parameterNames[i] + ":" + args[i]);
}
}
}
}
Parameter names are also logged:
Class******com.sun.proxy.$Proxy87
Interfaces******com.example.demoaspectmethodlogging.control.EmployeeRepository
Interfaces******org.springframework.data.repository.Repository
Interfaces******org.springframework.transaction.interceptor.TransactionalProxy
Interfaces******org.springframework.aop.framework.Advised
Interfaces******org.springframework.core.DecoratingProxy
Method******findByName
parameterNames******name:Simon
Upvotes: 1