CloudWatch for a Spring Boot App: JSON Logs, Micrometer Metrics From Your Own Code, and an Alarm That Reaches a Person
Relay's JSON log lines land in the log group /ecs/relay, kept 14 days. A hand-wired CloudWatch registry sends only relay.* metrics. Six calls to a ticket that fails answer 500, a log search finds exactly 6 ERROR lines, and the alarm relay-5xx goes from OK to ALARM and sends a text through SNS.
What you will learn
- Send structured JSON logs to a CloudWatch log group with a retention period
- Wire Micrometer's CloudWatch registry by hand in Spring Boot 4.1 and send only your own metrics
- Count server errors and log them in one place, so a metric and a log search agree
- Create an alarm on that metric that notifies a person through SNS
Before you start
- Structured Logging and Correlation IDs in Spring Boot: JSON Lines, a Filter and the MDC
- The AWS SDK for Java v2 in Spring Boot: Clients as Beans, the Default Credentials Chain and No Keys in Code
On AWS, CloudWatch is where Relay's logs, metrics and alarms meet. This article sets up all three for a small Spring Boot service: logs you can search, a metric from the app's own code, and an alarm that tells a person when something breaks. Everything ran against LocalStack 4.9, a local stand-in for AWS. On AWS, only the endpoint (empty) and the credentials (the task role) change.
Three signals, three places
| Signal | Where it goes | How it gets there |
|---|---|---|
| Logs | log group /ecs/relay | JSON lines on stdout; on ECS the awslogs driver ships them |
| Metrics | namespace Relay | Micrometer's CloudWatch registry, from the app |
| Alarm | relay-5xx on a metric | CloudWatch, then an SNS topic to a phone or mail |
AWS also gives some metrics for free, such as the load balancer's 5xx count and ECS CPU. They can't exist on a laptop, so they aren't shown here.
Logs: one JSON object per line
logging:
structured:
format:
console: ecs # one JSON object per line on stdout
The log group is created with a retention period, because CloudWatch keeps logs forever by default and charges for storage:
aws logs create-log-group --log-group-name /ecs/relay
aws logs put-retention-policy --log-group-name /ecs/relay --retention-in-days 14
describe-log-groups showed /ecs/relay 14. After three ticket calls, a search for lines containing "ticket " found them, each a full JSON object with log.level, log.logger, the thread and "message":"ticket 1 loaded". (Locally a small script shipped stdout to the log group, playing the part of the awslogs driver.)
Metrics: wired by hand
Spring Boot 4.1 has no auto-configuration for CloudWatch metrics; its actuator auto-configures registries such as Prometheus, not this one. So the project builds the registry itself, with micrometer-registry-cloudwatch2 and the SDK's CloudWatch client:
@Bean
CloudWatchAsyncClient cloudWatchClient(CloudWatchProperties props) {
CloudWatchAsyncClientBuilder b = CloudWatchAsyncClient.builder().region(Region.of(props.region()));
if (props.endpoint() != null && !props.endpoint().isBlank()) { // a local stand-in only
b.endpointOverride(URI.create(props.endpoint()));
}
return b.build();
}
@Bean
CloudWatchMeterRegistry cloudWatchRegistry(CloudWatchProperties props, CloudWatchAsyncClient client) {
CloudWatchConfig config = key -> switch (key) {
case "cloudwatch.namespace" -> props.namespace();
case "cloudwatch.step" -> props.step().toString();
default -> null;
};
CloudWatchMeterRegistry registry = new CloudWatchMeterRegistry(config, Clock.SYSTEM, client);
// every custom metric is billed: send only the relay.* ones
registry.config().meterFilter(MeterFilter.denyUnless(id -> id.getName().startsWith("relay.")));
return registry;
}
The namespace is Relay. The step is how often Micrometer sends: one minute by default (10 seconds in the demo run, so it didn't take long). And the filter matters most: Spring and the JVM produce dozens of metrics, and every custom metric in CloudWatch costs money. denyUnless sends only names that start with relay..
One place for a server error
@RestControllerAdvice
class ApiErrors {
private static final Logger log = LoggerFactory.getLogger(ApiErrors.class);
private final Counter serverErrors;
ApiErrors(MeterRegistry registry) {
this.serverErrors = registry.counter("relay.http.5xx");
}
@ExceptionHandler(IllegalStateException.class)
ResponseEntity<Map<String, String>> serverError(IllegalStateException ex) {
serverErrors.increment(); // the number the alarm watches
log.error("request failed: {}", ex.getMessage()); // and the line a log search finds
return ResponseEntity.status(500).body(Map.of("error", "internal"));
}
}
Every 500 goes through here, so the counter and the ERROR line always agree. list-metrics --namespace Relay showed two metrics: relay.http.5xx.count, and relay.tickets.value with the dimension status=open (a gauge in the controller). Micrometer adds .count and .value to the names it sends; the alarm has to use those exact names.
The alarm
{
"AlarmName": "relay-5xx",
"AlarmDescription": "Relay answered server errors",
"Namespace": "Relay",
"MetricName": "relay.http.5xx.count",
"Statistic": "Sum",
"Period": 60,
"EvaluationPeriods": 1,
"Threshold": 3,
"ComparisonOperator": "GreaterThanOrEqualToThreshold",
"TreatMissingData": "notBreaching",
"AlarmActions": ["<the relay-alerts topic>"]
}
In words: if the sum of 5xx answers in one 60-second period is 3 or more, go to ALARM and notify the relay-alerts SNS topic. TreatMissingData: notBreaching matters for a counter like this: a quiet minute sends no data at all, and that should count as fine, not as unknown. The topic has an SMS subscription; on AWS it texts or mails a person.
Break it: six errors
Ticket 13 is made to fail on purpose. Before, describe-alarms showed relay-5xx OK. Then six calls:
500 500 500 500 500 500
A log search for lines with "level":"ERROR" counted 6, and the first one read "message":"request failed: database timeout while loading ticket 13", logged by ApiErrors. Once the counter had been sent, describe-alarms showed relay-5xx ALARM. The SNS stand-in kept the message it was asked to send: AlarmName relay-5xx, OldStateValue OK, NewStateValue ALARM. On AWS, that's the text a person on call would get.
On AWS you'd use Logs Insights to search, for example filtering on log.level = "ERROR" and counting by message. It isn't run here; the local search used filter-log-events with the same idea.
Common mistakes
- A log group with no retention. It grows and bills forever.
- Sending every JVM metric to CloudWatch. Each one is a billed custom metric. Filter to what you alarm on or chart.
- Using the Micrometer name in the alarm. CloudWatch stores
relay.http.5xx.count, notrelay.http.5xx. - Missing data treated as breaching. A quiet night then looks like an outage.
- An alarm with no action. A red line on a dashboard nobody watches helps no one.
Try it yourself
Call ticket 13 only twice, wait a full minute, and check the alarm. Then call it three times within one minute. Which state does describe-alarms show each time, and why?
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Why Spring in 2026: What the Container Does and What Spring Framework 7 Changed
Spring in one line: a container that creates your classes and hands each one what it needs. Plus the Spring Framework 7 baseline (JDK 17 to 25, Jakarta EE 11, Tomcat 11, JUnit 6), what got better than Spring 6, and a two-line version check.
A Plain Spring Project, No Boot: Your First Bean With spring-context
One dependency, one recipe, one getBean: a Maven project with spring-context 7.0.9, a Blog record, an AppConfig with @Bean, and a main that asks the container for the Blog. Then delete @Bean and meet NoSuchBeanDefinitionException.
Inversion of Control and Dependency Injection in Spring: One Program, Built Three Ways
A PostService needs a PostRepository. Build it three ways: the service calls new itself (tight coupling), main hands it in through the constructor (DI by hand), and the Spring container does the wiring from a @Configuration recipe.
Spring Component Scanning: @Component and @ComponentScan Instead of @Bean Methods
Instead of one @Bean method per class, put @Component on EmailNotifier and PostService and @ComponentScan on an empty BlogConfig. Spring walks the package, finds the stickers and builds the beans; main doesn't change.
