Ultimate AspectJ method tracing

In last post and previous one I had shown how to setup AspectJ waving. There were also sample of simple method tracing. Here goes ultimate version:

package com.sample.utils;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MyLogger {

private static final Logger logger = LoggerFactory.getLogger(MyLogger.class);

public MyLogger() {

@Before("execution(* com.klasses..*(..))")
public void logBefore(JoinPoint point) {
logger.trace("Autotrace entry {}.{}({})", point.getSignature().getDeclaringTypeName(), point.getSignature()
.getName(), point.getArgs());

@AfterReturning(pointcut = "execution(* com.klasses..*(..))", returning = "result")
public void logAfter(JoinPoint point, Object result) {

boolean hasReturnValue = true;

if (point.getSignature() instanceof MethodSignature) {
hasReturnValue = !((MethodSignature) point.getSignature()).getReturnType().getCanonicalName().equals("void");

if (hasReturnValue) {
logger.trace("Autotrace exit {}.{}({}) returned {}", point.getSignature().getDeclaringTypeName(), point
.getSignature().getName(), point.getArgs(), result);
else {
logger.trace("Autotrace exit {}.{}({})", point.getSignature().getDeclaringTypeName(), point.getSignature()
.getName(), point.getArgs());


@AfterThrowing(pointcut = "execution(* com.klasses..*(..))", throwing = "error")
public void logThrow(JoinPoint point, Throwable error) {
logger.trace("Autotrace exit {}.{}({}) throwed {}", point.getSignature().getDeclaringTypeName(), point
.getSignature().getName(), point.getArgs(), error);


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s