lundi 14 février 2022

Micronaut AOP on package to capture execution time of each method

To capture logTime of each controller call, I added @LogTime annotation for package level but it is not working. I am not able to figure out why it is working with ElementType.TYPE at class level annotation but not with ElementType.PACKAGE at package level. Could you please help?

package com.test.aop;

import io.micronaut.aop.Around;
import io.micronaut.context.annotation.Type;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PACKAGE})
@Around
@Type(LogTimeInterceptor.class)
public @interface LogTime {
}

LogTimeInterceptor

package com.test.aop;

import io.micronaut.aop.MethodInterceptor;
import io.micronaut.aop.MethodInvocationContext;
import javax.inject.Singleton;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StopWatch;

@Singleton
public class LogTimeInterceptor implements MethodInterceptor<Object, Object> {
    private static final Logger LOGGER = LoggerFactory.getLogger(LogTimeInterceptor.class);

    @Override
    public Object intercept(MethodInvocationContext<Object, Object> context) {
        var timer = new StopWatch(context.getDeclaringType().getSimpleName() + "." + context.getName());
        try {
            timer.start();
            return context.proceed();
        } finally {
            timer.stop();
            LOGGER.info("StopWatch Task name:{} running time:{} sec", timer.getId(), timer.getTotalTimeSeconds());
        }
    }
}

package-info.java

@LogTime
package com.tet.controllers;

import com.test.aop.LogTime;




Aucun commentaire:

Enregistrer un commentaire