How can I start and stop a timer in different classes?

寵の児 提交于 2019-12-13 02:15:20

问题


I want to measure the time from the start of an incoming HTTP request and the application getting to a certain point. Both those points in time are located in different classes. How would I start and stop a timer from these different classes. I don't see a way to use 'named' timers from the MeterRegistry.

How would I go about this?


回答1:


You can use AOP as below :

@Aspect
@Component
public class ControllerMonitor {

    protected static  final Logger LOGGER = LoggerFactory.getLogger(ControllerMonitor.class);


    @Before("execution(public * com.demo.controller.*Controller.*(..))")
    public void logBeforeAccess(JoinPoint joinPoint) {
        if(joinPoint!=null){
            String packageName = joinPoint.getSignature()!=null?joinPoint.getSignature().getDeclaringTypeName():"LOG-404";
            LOGGER.info(". . .A request initiated from controller [" + packageName + "."+ getMethodSignature(joinPoint) +  "]. . .");
        }

    }

    @After("execution(public * com.demo.controller.*Controller.*(..))")
    public void logAfterAccess(JoinPoint joinPoint) {
        if(joinPoint!=null){
            String packageName = joinPoint.getSignature()!=null?joinPoint.getSignature().getDeclaringTypeName():"LOG-404";
            LOGGER.info(". . .Request from controller [" + packageName + "."+ getMethodSignature(joinPoint) +  "] completed. . .");
        }
    }

    @AfterThrowing(pointcut = "execution(public * com.demo.controller.*Controller.*(..))",throwing="exception")
    public void logAfterThrowing(Exception exception){
        LOGGER.error("Exception caught:"+ exception.getMessage());
    }

    private String getMethodSignature(JoinPoint joinPoint){
        if(joinPoint!=null){
            String methodName = joinPoint.getSignature().getName();
            Object[] arguments = joinPoint.getArgs();
            StringBuilder sb=new StringBuilder();
            if(arguments!=null){
                for (Object param: arguments) {
                    sb.append(param).append(",");
                }
                sb =(sb.length()>1)?sb.deleteCharAt(sb.length()-1):sb;
            }
            methodName = methodName+"("+new String(sb)+")";
            return methodName;
        }else{
            return "LOG-405";
        }
    }
}



回答2:


Use AOP …...No need to do changes on each class level. It will be one place config..



来源:https://stackoverflow.com/questions/55948389/how-can-i-start-and-stop-a-timer-in-different-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!