4: Monitoring and Logging

    Collection, Aggregation, and Storage of Logs and Metrics

    Observability for a professional DevOps surface starts with a deliberate decision about what to collect, where it lands, and how it travels from the workload to the analyst's screen. The wrong default is to enable everything available and discover at month end that ingest cost has outrun compute. The right default is to map every workload tier to a collection mechanism, a destination, and a retention horizon that match how the data is actually used: short windows for live troubleshooting, medium windows for trend analysis, and long windows for compliance evidence. The pipeline that connects these tiers must also degrade gracefully when a downstream system is unavailable, because losing observability during an incident is precisely the moment when the data is most needed.

    The AWS plane provides three first-class collection channels. CloudWatch Logs is the line-buffered text and JSON channel for application stdout, the CloudWatch agent's tail of system files, container stdout via the awslogs log driver, and managed services such as AWS Lambda or Amazon API Gateway. CloudWatch metrics is the time-series channel for numeric measurements, populated automatically by most managed services and explicitly by the PutMetricData API, the CloudWatch agent's metrics block, or the embedded metric format. AWS X-Ray and the OpenTelemetry traces ingestion endpoint form the trace channel for distributed call graphs. Almost every operational decision in this chapter reduces to choosing the right channel for the data shape and the right downstream sink for the access pattern.

    A workload's collection topology is never one box wide. A typical fleet of Amazon EC2 instances writes application logs and system logs through the CloudWatch agent into CloudWatch Logs, emits custom application metrics through embedded metric format, exposes X-Ray segments through the X-Ray daemon or the AWS Distro for OpenTelemetry collector, and relies on the host instance metrics pulled automatically through the CloudWatch agent. Containers running on Amazon ECS or AWS Fargate route the same data through the awslogs or the AWS for Fluent Bit log router, with Container Insights enabled for performance metrics. AWS Lambda functions write to CloudWatch Logs through the runtime, emit embedded metric format records on stdout, and integrate with X-Ray through the active-tracing flag. The DevOps engineer's job is to make these channels deliberate, idempotent, and verifiable.

    Aggregation is the second concern. A workload spread across three AWS Regions and twenty AWS accounts has no single pane of glass until the observability data is either physically copied to one place or made queryable from one place. CloudWatch Logs subscription filters move data out of the per-Region log group plane into Amazon Kinesis Data Streams, Amazon Data Firehose, AWS Lambda, or Amazon OpenSearch Service. Metric streams move metric data points out of CloudWatch metrics into Amazon Data Firehose, an HTTP endpoint, or third-party observability vendors. CloudWatch cross-account observability links a monitoring account to many source accounts so a single CloudWatch console renders logs, metrics, traces, and dashboards from all of them, including the cross-account version of CloudWatch Logs Insights and the X-Ray service map.

    Storage decisions decide cost. CloudWatch Logs charges for ingestion plus storage; Amazon S3 charges only for storage plus a small request fee; Amazon OpenSearch Service charges for the cluster plus the storage. A log group whose only purpose is monthly evidence collection wastes money sitting in CloudWatch Logs for three years when an export to S3 with an S3 Glacier Deep Archive lifecycle rule would store the same data at a fraction of the cost. A log group whose purpose is incident triage during the next hour belongs in CloudWatch Logs precisely because Logs Insights queries it in seconds. The pattern that recurs throughout this chapter is the split-channel pattern: hot data in CloudWatch Logs, warm data in OpenSearch Service, cold data in Amazon S3.

    Configuring metric filters and subscription filters in CloudWatch Logs

    Metric filters and subscription filters are the two extension points that turn a passive log group into an active signal. A metric filter scans the lines that arrive at a log group, parses them with either a JSON expression or a space-delimited pattern, and emits a CloudWatch metric data point whose value comes from the matched fields or from a literal count. A subscription filter is the stream sibling: it forwards matching lines to a delivery target, typically a Kinesis Data Stream, an Amazon Data Firehose stream, an AWS Lambda function, or a destination ARN in another account.

    A metric filter is the right tool when the question is "how often does X happen", because the resulting metric integrates the count over time and supports alarms. A subscription filter is the right tool when the question is "I need to react to or store this line", because the filter delivers the full event to the downstream consumer. The two are not mutually exclusive: a production design routinely runs a metric filter for alarming and a subscription filter for downstream analytics on the same log group.

    aws logs put-metric-filter \
     --log-group-name /aws/lambda/checkout-service \
     --filter-name CheckoutErrorRate \
     --filter-pattern '{ $.level = "ERROR" && $.component = "checkout" }' \
     --metric-transformations '[
     {
     "metricName": "CheckoutErrors",
     "metricNamespace": "Acme/Checkout",
     "metricValue": "1",
     "defaultValue": 0,
     "unit": "Count"
     }
     ]'
    

    The defaultValue: 0 clause is the detail that converts an episodic counter into a time-series suitable for alarming: without it the metric only emits when a match occurs and the alarm cannot evaluate a "less than 1 over five periods" condition because missing data periods are not the same as zero. The exam reads this distinction routinely.

    Subscription filters extend the design to a streaming consumer. A common pattern is to fan log lines into Amazon OpenSearch Service through Amazon Data Firehose with a Lambda transform that flattens nested JSON before indexing.

    aws logs put-subscription-filter \
     --log-group-name /aws/ecs/orders-cluster \
     --filter-name AllOrdersToFirehose \
     --filter-pattern '' \
     --destination-arn arn:aws:firehose:us-east-1:111122223333:deliverystream/orders-to-opensearch \
     --role-arn arn:aws:iam::111122223333:role/CWLtoFirehoseRole \
     --distribution Random
    

    The empty filter-pattern ships every line, which is appropriate for full-text search downstream. The distribution attribute determines how Kinesis sends shards: Random for even spread, ByLogStream to keep one stream's lines together for ordering. A log group accepts at most two subscription filters, so a hub-and-spoke design at scale typically uses a single subscription to a Kinesis Data Stream from which several consumers read.

    💡 Exam Trap: A CloudWatch Logs subscription filter forwards events as a base64-encoded gzipped payload, not as plain JSON. A Lambda consumer that does not decompress the payload before parsing will report "invalid JSON" on every invocation. The X-Ray daemon and the OpenSearch Service ingestion Lambda template handle this automatically; a hand-rolled consumer must not.

    💡 Exam Trap: A metric filter that omits defaultValue produces a sparse time-series. An alarm with treatMissingData=missing over a sparse series can flap between ALARM and INSUFFICIENT_DATA in a way that suppresses pages. The fix is to set defaultValue: 0 on the filter, not to change treatMissingData to notBreaching.

    ⚠️ Anti-Pattern: Putting one subscription filter per consumer on the same log group fails when more than two consumers are required. The right shape is a single subscription filter to a Kinesis Data Stream and one consumer per stream shard application, each tracking its own iterator.

    Automating operational response actions for events

    The observability layer is most valuable when the response to an event runs without a human. The pattern is built from three pieces: a signal source (a CloudWatch alarm state change, an EventBridge event, or an AWS Health event), a rule that filters the source, and a target that performs the action. The target is almost always either an AWS Lambda function for code paths or an AWS Systems Manager Automation runbook for procedural paths. Lambda is the right answer when the response requires custom logic, multiple API calls, or third-party integrations; an Automation runbook is the right answer when the response is a sequence of well-known AWS API calls, especially when an approval step or fleet-wide execution is involved.

    Resources:
     AlarmToSsmRule:
     Type: AWS::Events::Rule
     Properties:
     EventBusName: default
     EventPattern:
     source: ["aws.cloudwatch"]
     detail-type: ["CloudWatch Alarm State Change"]
     detail:
     state:
     value: ["ALARM"]
     alarmName: [{ "prefix": "prod-checkout-" }]
     Targets:
     - Id: RestartTargetFleet
     Arn: !Sub arn:aws:ssm:${AWS::Region}::automation-definition/AWS-RestartEC2Instance
     RoleArn: !GetAtt EventBridgeToSsmRole.Arn
     InputTransformer:
     InputPathsMap:
     instances: "$.detail.configuration.metrics[0].metricStat.metric.dimensions.InstanceId"
     InputTemplate: '{ "InstanceId": [<instances>] }'
    

    The InputTransformer block illustrates a recurrent professional concern: the event payload is rarely shaped exactly the way the target expects, so the rule reshapes it before delivery. EventBridge supports JSONPath extraction ($.detail...) and a template string. The Systems Manager Automation document then performs the actual remediation through aws:executeAwsApi, aws:executeAutomation, or aws:executeScript steps, with optional approval gates.

    🎯 Scenario: A nightly batch fails because the Amazon RDS for PostgreSQL instance is at 95 percent CPU. The alarm prod-batch-cpu-high fires. An EventBridge rule on the alarm state change invokes an SSM Automation runbook that calls aws rds modify-db-instance to step up the instance class one tier and reports back through Amazon SNS. The DevOps engineer reviews the change in the morning and either accepts it as a permanent right-sizing or reverts. The point is that the alert and the action are wired together; nobody is paged at 02:00.

    Decision Anchor: choose a CloudWatch alarm action with an SNS topic feeding a Lambda function when the response is custom code with non-AWS API calls. Choose an EventBridge rule on the CloudWatch Alarm State Change event with an SSM Automation runbook target when the response is a sequence of AWS API calls, especially when an approval gate is involved.

    💡 Exam Trap: An alarm action can directly invoke an SSM Automation document, an Amazon EC2 action (stop, terminate, reboot, recover), an Auto Scaling action, or an SNS topic. It cannot directly invoke a Lambda function. To reach Lambda, the alarm publishes to SNS and the Lambda subscribes, or the alarm state change is routed through EventBridge to Lambda. Picking "alarm directly invokes Lambda" on the exam is wrong.

    ⚠️ Anti-Pattern: Wiring auto-remediation directly to every alarm without a circuit breaker. A flaky metric can cause the remediation to run hundreds of times an hour. The defense is either a composite alarm that requires the symptom to persist across multiple sub-alarms, or a Lambda function that records its previous execution and exits early if it has already remediated within a cooldown window.

    The remainder of the observability stack examined in this chapter rests on the collection, filtering, and forwarding patterns described above. Every downstream feature, from cross-account dashboards to anomaly-detection alarms, presumes that the data reached the right log group, with the right encryption, the right retention, and the right downstream subscribers wired through CloudFormation or AWS CDK rather than through one-off console clicks.


    Continue with the interactive course

    Track your progress, jump into practice questions and use the Shark AI tutor inside the AWS - DevOps Engineer Professional learning hub.