问题
I want to implement the ability to log entry and exit of some methods that are annotated with some annotation (For example: @Loggable
). I came across AspectJ AOP using which we can do this.
I implemented a custom aspect of my own to customise the log message I want to print on entry and exit of the method that gets called with @Loggable
:
@Aspect
public final class MethodLogger {
private static final Logger LOG = LoggerFactory.getLogger(MethodLogger.class);
@Around("execution(* *(..)) && @annotation(Loggable)")
public Object around(ProceedingJoinPoint point) throws Throwable {
String className = MethodSignature.class.cast(point.getSignature()).getClass().getName();
String methodName = MethodSignature.class.cast(point.getSignature()).getMethod().getName();
LOG.info(
"Entering method:{}() of class:{} with parameters: {}",
methodName,
className,
Arrays.toString(point.getArgs()));
try
{
return point.proceed();
}
catch(Throwable e){
throw e;
}
finally
{
LOG.info(
"Exiting method:{}() of class:{} with parameters: {}",
methodName,
className,
Arrays.toString(point.getArgs()));
}
}
}
pom.xml dependencies:
<dependency>
<groupId>com.jcabi</groupId>
<artifactId>jcabi-aspects</artifactId>
<version>0.22.5</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.9.1</version>
</dependency>
Class that has a method annotated with @Loggable
:
@Component
public class LoginPage extends BasePage {
@Loggable
public Object login(String username, String password) {
}
}
Problem:
When this instance method (login()
)is called mostly in the following manner:
loginPage.login()
, I cannot see the entry and exit log being printed to the log output.
Please note:
- I am using Spring dependency injection to initialise such classes with
@Component
annotation, not sure if that is useful information for the forum but still letting you all know. - This is a test automation project where I am triggering some UI automated tests from a JUnit+Cucumber runner class.
- I am not triggering my tests from maven.
Can someone suggest what could be going wrong here?
回答1:
You aspect MethodLogger
is not initialized yet.Try adding @Component
to the MethodLogger
. This should load and register the aspect into the context, making it ready for use.
Also you might want to simplify your point cut @Around("execution(* *(..)) && @annotation(Loggable)")
.
execution(* *(..))
is basically a wild card and therefore useless. Just use@Around("@annotation(Loggable)")
.
来源:https://stackoverflow.com/questions/51358784/method-with-loggable-annotation-never-prints-aspect-log