Last active
December 15, 2023 15:52
-
-
Save fastnsilver/15f4fee29bf324d6d7d0 to your computer and use it in GitHub Desktop.
How to configure AWS CloudWatch metrics w/ Spring Boot
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Modeled after {@link org.springframework.cloud.netflix.servo.ServoMetricCollector} | |
// employed explicitly for publication of AWS CloudWatch metrics | |
public class CloudWatchMetricCollector { | |
private final Logger log = LoggerFactory.getLogger(getClass()); | |
@Value("${spring.aws.cloudwatch.metrics.polling.timeUnit:SECONDS}") | |
private String timeUnit; | |
@Value("${spring.aws.cloudwatch.metrics.polling.interval:5}") | |
private int pollingInterval; | |
@Value("${spring.application.name}") | |
private String applicationName; | |
@Autowired | |
private AWSCredentials awsCredentials; | |
public CloudWatchMetricCollector() { | |
List<MetricObserver> observers = new ArrayList<MetricObserver>(); | |
observers.add(new CloudWatchMetricObserver(applicationName, "servo.cloudwatch", new AmazonCloudWatchAsyncClient(awsCredentials))); | |
PollRunnable task = new PollRunnable(new MonitorRegistryMetricPoller(), | |
BasicMetricFilter.MATCH_ALL, true, observers); | |
if (!PollScheduler.getInstance().isStarted()) { | |
try { | |
PollScheduler.getInstance().start(); | |
} | |
catch (Exception e) { | |
// Can fail due to race condition with evil singletons (if more than one | |
// app in same JVM) | |
log.error("Could not start AWS CloudWatch metrics poller", e); | |
return; | |
} | |
} | |
PollScheduler.getInstance().addPoller(task, pollingInterval, TimeUnit.valueOf(timeUnit)); | |
} | |
@PreDestroy | |
public void destroy() throws Exception { | |
log.info("Stopping Servo PollScheduler"); | |
if (PollScheduler.getInstance().isStarted()) { | |
try { | |
PollScheduler.getInstance().stop(); | |
} | |
catch (Exception e) { | |
log.error("Could not stop servo metrics poller", e); | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Configuration | |
@ConditionalOnAwsCloudEnvironment | |
@EnableContextCredentials | |
public class CloudWatchMetricsConfig { | |
@Bean | |
public CloudWatchMetricCollector cloudWatchMetricCollector() { | |
return new CloudWatchMetricCollector(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
And an alternate way is: https://gist.github.com/fastnsilver/ed6948e0f2e464b52d5f