Subversion Repositories SmartDukaan

Rev

Rev 34563 | Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
34554 tejus.loha 1
package com.smartdukaan.cron.monitored;
2
 
3
import java.util.Date;
4
import java.util.Map;
5
import java.util.concurrent.ConcurrentHashMap;
6
import java.util.concurrent.TimeUnit;
7
 
8
import io.micrometer.core.instrument.Counter;
9
import org.aspectj.lang.ProceedingJoinPoint;
10
import org.aspectj.lang.annotation.Around;
11
import org.aspectj.lang.annotation.Aspect;
12
import org.springframework.beans.factory.annotation.Autowired;
13
import org.springframework.stereotype.Component;
14
 
15
import io.micrometer.core.instrument.MeterRegistry;
16
import org.slf4j.Logger;
17
import org.slf4j.LoggerFactory;
18
 
19
/**
20
 * Aspect to monitor execution of cron jobs via metrics and logging.
21
 */
22
@Aspect
23
@Component
24
public class CronJobMonitorAspect {
25
 
26
    private static final Logger log = LoggerFactory.getLogger(CronJobMonitorAspect.class);
27
 
28
    @Autowired
29
    private MeterRegistry meterRegistry;
30
 
31
    private final Map<String, Counter> failureCounters = new ConcurrentHashMap<>();
32
 
33
 
34
    /**
35
     * Intercept any method annotated with @Scheduled (i.e. cron jobs).
36
     */
37
    @Around("@annotation(org.springframework.scheduling.annotation.Scheduled)")
38
    public Object monitorCronJob(ProceedingJoinPoint joinPoint) throws Throwable {
39
        String methodName = joinPoint.getSignature().toShortString();
40
        log.info("Cron job {} started", methodName);
41
        System.out.println("Cron job " + methodName + " started");
42
        long startTime = System.currentTimeMillis();
43
 
44
        try {
45
            // Proceed with the scheduled method
46
            Object result = joinPoint.proceed();
47
            long elapsed = System.currentTimeMillis() - startTime;
48
 
49
            log.info("Cron job {} completed successfully in {} ms", methodName, elapsed);
50
            System.out.println("Cron job " + methodName + " completed successfully in " + elapsed + " ms");
51
 
52
            try {
53
                meterRegistry.counter("custom.cron.success.count", "method", methodName, "status", "success")
54
                        .increment();
55
                meterRegistry.timer("custom.cron.execution.time", "method", methodName, "status", "success")
56
                        .record(elapsed, TimeUnit.MILLISECONDS);
57
            } catch (Exception e) {
58
                log.warn("Failed to update success metrics for {}: {}", methodName, e.toString());
59
            }
60
 
61
            return result;
62
        } catch (Throwable ex) {
63
            long elapsed = System.currentTimeMillis() - startTime;
64
            log.error("Cron job {} failed in {} ms: {}", methodName, elapsed, ex.toString());
65
            System.out.println("Cron job " + methodName + " failed in " + elapsed + " ms");
66
 
67
            try {
68
                meterRegistry.counter("custom.cron.failure.count", "method", methodName, "status", "failure")
69
                        .increment();
70
                meterRegistry.timer("custom.cron.execution.time", "method", methodName, "status", "failure")
71
                        .record(elapsed, TimeUnit.MILLISECONDS);
72
            } catch (Exception e) {
73
                log.warn("Failed to update failure metrics for {}: {}", methodName, e.toString());
74
            }
75
            getFailureCounter(methodName).increment();
76
            throw ex;
77
        }
78
    }
79
 
80
    private Counter getFailureCounter(String methodName) {
81
        return failureCounters.computeIfAbsent(methodName, name ->
82
                Counter.builder("cron_execution_failure_count_total")
83
                        .description("Number of failed executions of scheduled method")
84
                        .tag("method", name)
85
                        .register(meterRegistry)
86
        );
87
    }
88
}