java

Profiling with Spring

Every application should have functional and non-functional tests. Non-functional include load and performance. So what happens when we do not meet the performance requirements? Obviously we try to figure out what is going on. This is called profiling. In this post I will write about how to profile an application with spring.

joao-silas-72563-unsplash

Photo by João Silas on Unsplash

Profiling an application is a cross-cutting concern so it fits under the hood of aspect oriented programming. That means we need to define an aspect.

@Aspect
@Component
public class ProfileExecutionAspect {

    @Pointcut(value = "execution(public * *(..))")
    public void anyPublicMethod() {
    }

    @Around("anyPublicMethod() && @annotation(ProfileExecution)")
    public Object profileExecuteMethod(ProceedingJoinPoint jointPoint) throws Throwable {
        Signature signature = jointPoint.getSignature();
        String methodName = signature.toShortString();

        StopWatch stopWatch = new StopWatch(ProfileExecutionAspect.class.getName());
        stopWatch.start(methodName);

        Object result = jointPoint.proceed();

        stopWatch.stop();
        //log not sysout
        System.out.println(stopWatch.prettyPrint());
        return result;
    }
}

Here we have the point-cut annotated with @Pointcut. The execution of any public method which is annotated with @ProfileExecution. This way we can target any method. @Around is the most powerful type of advice, we have more control by using it.

The @ProfileExecution is just a simple annotation.

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Inherited
@Documented
public @interface ProfileExecution {
}

That’s it. Just annotate your method with @ProfileExecution and check the logs. Simple enough.

Advertisements

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s