Subversion Repositories SmartDukaan

Rev

Rev 34578 | Blame | Compare with Previous | Last modification | View Log | RSS feed

package com.smartdukaan.cron.monitored;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;

import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.Timer;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import io.micrometer.core.instrument.MeterRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Aspect
@Component
public class CronJobMonitorAspect {

    private static final Logger log = LoggerFactory.getLogger(CronJobMonitorAspect.class);

    @Autowired
    private MeterRegistry meterRegistry;

    private final ConcurrentMap<String, AtomicInteger> lastStatus = new ConcurrentHashMap<>();

    @Around("@annotation(org.springframework.scheduling.annotation.Scheduled)")
    public Object monitorCronJob(ProceedingJoinPoint joinPoint) throws Throwable {
        String methodName = joinPoint.getSignature().getName();
        lastStatus.computeIfAbsent(methodName, m -> {
            AtomicInteger gauge = new AtomicInteger(0);
            Gauge.builder("cron_job_last_status", gauge, AtomicInteger::get)
                    .description("1=success, 0=failure")
                    .tag("method", m)
                    .register(meterRegistry);
            return gauge;
        });

        boolean success = false;

        // Start a timer sample
        Timer.Sample sample = Timer.start(meterRegistry);
        try {
            Object result = joinPoint.proceed();
            success = true;
            // Record a success count
            meterRegistry.counter(
                    "cron_job_count_total", "method", methodName, "status", "success").increment();
            return result;
        } catch (Throwable t) {
            // Record a failure count with exception type
            meterRegistry.counter(
                    "cron_job_count_total", "method", methodName, "status", "failure").increment();
            throw t;
        } finally {
            sample.stop(Timer.builder("cron_job_duration_seconds")
                    .tag("method", methodName)
                    .register(meterRegistry));
            lastStatus.get(methodName).set(success ? 1 : 0);

        }
    }

}