[SpringBoot] Add custom metric in spring boot application and show in AWS CloudWatch

Application Performance Monitoring is one of the method to ensure application’s availability and status. However, most of them only can check the platform status (e.g. CPU usage / Thread / Memory / etc), some organization will define application healthiness with some custom business logic (e.g. no. of order failure, etc) to indicate its perform normal or not.

In this demo, it will use springboot actuator to capture metric and AWS cloudwatch to render it out.Steps as below:

  1. Add related library.
    In build.gradle, add dependency as below.

    dependencies {
        compile('org.springframework.boot:spring-boot-starter-web')
        compile('org.springframework.cloud:spring-cloud-starter-aws:2.2.5.RELEASE')
        compile('org.springframework.boot:spring-boot-starter-aop')
        compile("org.springframework.boot:spring-boot-starter-actuator")
        compile('org.springframework.cloud:spring-cloud-aws-actuator:2.2.5.RELEASE')
    }
  2. Add annotation in Main application.
    In application.java, alter code as below.

    @EnableAspectJAutoProxy
    @SpringBootApplication
    @EnableAutoConfiguration(exclude = {ContextInstanceDataAutoConfiguration.class})
    @EnableScheduling
    public class Application {
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
    }
    

     

  3. Create metrics and register in Meter Registry.
    Create controller DiagnoisisController and alter code as below.

    @RestController("DiagnosisController")
    @RequestMapping(value ="/v1/diagnosis")
    public class DiagnosisController {
        @Autowired
        DiagnosisService diagnosisService;
    
        public static final long METRIC_RELOAD_INTERVAL=10000;
        public static final String METRIC CLIENT_COUNT="connection.count";
        public static final String METRIC_THALES_CLIENT_COMPLETED_TASK_COUNT="client.completed.tasks";
    
        private final AtomicInteger currentHsmClientCount;
        private final Counter currentThalesClientCompletedTaskCount;
    
        public DiagnosisController(MeterRegistry meterRegistry) throws Exception {
            currentHsmClientCount=meterRegistry.gauge(METRIC_HSM_CLIENT_COUNT, new AtomicInteger());
            currentThalesClientCompletedTaskCount= Counter.builder(METRIC_THALES_CLIENT_COMPLETED_TASK_COUNT).description("Thales client completed tasks.").register(meterRegistry);
        }
    
        @Scheduled(fixedRate = METRIC_RELOAD_INTERVAL)
        public void updateMetric() throws Throwable {
            ServiceStatus serviceStatus=diagnosisService.status(false);
            currentHsmClientCount.set(serviceStatus.getCurrentClientCount());
            currentThalesClientCompletedTaskCount.increment(serviceStatus.getCurrentClientCompletedTaskCount());
        }
    }

    Method updateMetric() is used to update metric value with schedule job. Normally it can return object count / size, but my case is return service response so it’s not valid in there.

  4. Add AWS metric properties.
    In application.properties, add settings as below.

    ## Springboot Actuator settings.
    management.endpoint.health.show-details=always
    management.endpoints.web.exposure.include=*
    management.health.db.enabled=true
    
    ## AWS Cloudwatch settings.
    cloud.aws.region.static=[[AWS available zone code]]
    cloud.aws.stack.auto = false
    management.metrics.export.cloudwatch.namespace=[Display name in CloudWatch]
    management.metrics.export.cloudwatch.batchSize=20
  5. Check result locally.
    Run debug in IDE, open /actuator/metrics/ , see custom metric found or not. Expected it is exists.
  6. Check result in CloudWatch
    After deploy to AWS EC2 instance, CloudWatch will capture metric automatically.
About C.H. Ling 262 Articles
a .net / Java developer from Hong Kong and currently located in United Kingdom. Thanks for Google because it solve many technical problems so I build this blog as return. Besides coding and trying advance technology, hiking and traveling is other favorite to me, so I will write down something what I see and what I feel during it. Happy reading!!!

1 Trackback / Pingback

  1. [.net core] Add healthcheck in .net core backend service - Ling's Note

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.