Ravindra BagaleCourses & study guides मराठी

Chapter 14: Logging and Light Observability

DevOps

14.11c From red metric to log line (glue with Chapter 13)

Why: the problem

Suppose a CloudWatch alarm wakes you at 3 a.m. It says: 5xx errors on the Zomato-like order API crossed 50 per minute. A metric tells you something is wrong, but not why. Your job is to go from that red line on a graph to the exact log line that explains it, fast. The path is always the same. Note the alarm time window. Open the logs for that service in that window. Filter errors. Group them by message. Read the first one and its request id. Then follow the id. In this lesson we build that path end to end: a metric filter, an alarm, an SNS email, and the saved Logs Insights query that takes you from the alarm to the cause in under five minutes.

What we will build

You will create a metric filter on 5xx log lines, an alarm on it that emails you through SNS, cause errors with a small load script, and then go from the alarm to the root-cause log line with saved Logs Insights queries. You will also see the same flow with Prometheus and Loki in Grafana.

What: every term in plain English

  • Metric filter — A CloudWatch rule that counts matching log lines as a metric.
  • Alarm — A rule that watches a metric and changes state to ALARM when it crosses a threshold.
  • Threshold — The limit, like more than 50 errors in 1 minute.
  • SNS — Simple Notification Service. Sends the alarm by email, SMS or to Slack via a hook.
  • Alarm window — The time when the metric was red. Search logs only in this window.
  • Runbook link — A link in the alarm description to the steps to follow.
  • Loki — Grafana's log store. Its query language is LogQL.
  • Drill down — Going from a graph to the exact log lines behind it.
Make an SNS topic Subscribe your email Metric filter for 5xx JSON lines Alarm Cause errors Watch the state
Drill down: alarm to time window to group errors to first error to request id

How: step by step

  1. Make an SNS topic

    aws sns create-topic --name loglab-alerts --query TopicArn --output text
    

    What it does: Where alarms send messages.

    Output

    arn:aws:sns:ap-south-1:111122223333:loglab-alerts
    
  2. Subscribe your email

    aws sns subscribe --topic-arn arn:aws:sns:ap-south-1:111122223333:loglab-alerts --protocol email --notification-endpoint you@example.com
    

    What it does: Click the confirm link in your inbox.

    Output

    "SubscriptionArn": "pending confirmation"
    
  3. Metric filter for 5xx JSON lines

    aws logs put-metric-filter --log-group-name /loglab/orders --filter-name http5xx --filter-pattern '{ $.status >= 500 }' --metric-transformations metricName=Orders5xx,metricNamespace=LogLab,metricValue=1,defaultValue=0
    

    What it does: Every 5xx line adds 1.

    Output

    (no output)
    
  4. Alarm

    aws cloudwatch put-metric-alarm --alarm-name orders-5xx --namespace LogLab --metric-name Orders5xx --statistic Sum --period 60 --evaluation-periods 1 --threshold 50 --comparison-operator GreaterThanThreshold --treat-missing-data notBreaching --alarm-actions arn:aws:sns:ap-south-1:111122223333:loglab-alerts --alarm-description "Runbook: open saved query orders-5xx-top"
    

    What it does: ALARM when more than 50 errors in one minute.

    Output

    (no output)
    
  5. Cause errors

    python load.py
    

    What it does: Sends 80 error lines in one minute (Example 1).

    Output

    sent 80 error events
    
  6. Watch the state

    aws cloudwatch describe-alarms --alarm-names orders-5xx --query "MetricAlarms[0].StateValue"
    

    What it does: After about a minute it turns to ALARM.

    Output

    "ALARM"
    

Example 1: Load script that writes realistic 5xx JSON logs

Stack. Python, boto3, CloudWatch alarms, SNS

Goal. Load script that writes realistic 5xx JSON logs.

load.py

import json, random, time, uuid, boto3

logs = boto3.client("logs", region_name="ap-south-1")
G, S = "/loglab/orders", "api-1"
try:
    logs.create_log_group(logGroupName=G)
except logs.exceptions.ResourceAlreadyExistsException:
    pass
try:
    logs.create_log_stream(logGroupName=G, logStreamName=S)
except logs.exceptions.ResourceAlreadyExistsException:
    pass

now = int(time.time() * 1000)
events = []
for i in range(80):
    msg = random.choice(["db pool exhausted", "db pool exhausted", "upstream menu timeout"])
    events.append({"timestamp": now + i, "message": json.dumps({
        "level": "ERROR", "status": 500, "path": "/orders", "msg": msg,
        "request_id": uuid.uuid4().hex, "ms": random.randint(2900, 3100)})})
logs.put_log_events(logGroupName=G, logStreamName=S, logEvents=events)
print("sent", len(events), "error events")

What each line does

  • json.dumps({...}) — Each event is a JSON line, so the filter can read $.status.
  • random.choice(...) — Two kinds of errors, one more common, like real life.
  • request_id — So we can follow one failing request later.
  • put_log_events(... events) — One batch of 80 events.

Green output

$ python load.py
sent 80 error events
$ aws cloudwatch describe-alarms --alarm-names orders-5xx --query "MetricAlarms[0].[StateValue,StateReason]"
[
    "ALARM",
    "Threshold Crossed: 1 datapoint [80.0 (25/10/26 07:31:00)] was greater than the threshold (50.0)."
]

Expected result. The alarm fired and the email says 80 errors at 07:31 UTC (13:01 IST).

Example 2: From the alarm to the cause with Logs Insights

Stack. CloudWatch Logs Insights

Goal. From the alarm to the cause with Logs Insights.

Query 1: what failed most (save as orders-5xx-top)

filter status >= 500
| stats count(*) as n by msg, path
| sort n desc
| limit 5

Query 2: the first error in the window

filter status >= 500
| sort @timestamp asc
| limit 1
| fields @timestamp, msg, request_id, ms

Query 3: follow one request id in all groups

filter request_id = "6f1c2a9e4b7d4c1e9a3f2d8e1b7c5a90"
| sort @timestamp asc

What each line does

  • Set time to the alarm window — For example 07:25 to 07:35 UTC. Small window, fast and cheap query.
  • stats count(*) by msg, path — Groups 80 lines into 2 messages.
  • sort @timestamp asc | limit 1 — The very first error: often the trigger.
  • filter request_id — Follow the story of one request.

Green output

msg                     path      n
db pool exhausted       /orders   54
upstream menu timeout   /orders   26

@timestamp     msg                 request_id                         ms
07:31:00.000   db pool exhausted   6f1c2a9e4b7d4c1e9a3f2d8e1b7c5a90   3012

Expected result. Root cause guess: the database connection pool is too small. The menu timeouts are a side effect.

Example 3: Same drill down with Prometheus and Loki in Grafana

Stack. Prometheus, Grafana, Loki, Docker

Goal. Same drill down with Prometheus and Loki in Grafana.

PromQL (alert expression)

sum(rate(http_requests_total{job="orders", status=~"5.."}[1m])) > 50

LogQL in Grafana Explore (Loki)

{app="orders"} | json | status >= 500
sum by (msg) (count_over_time({app="orders"} | json | status >= 500 [5m]))

Run Loki and Grafana for practice

docker network create obs
docker run -d --name loki --network obs -p 3100:3100 grafana/loki:3.0.0
docker run -d --name grafana --network obs -p 3001:3000 grafana/grafana:11.2.0
curl -s localhost:3100/ready

What each line does

  • rate(...[1m]) — Errors per second over 1 minute.
  • status=~"5.." — Any 5xx code.
  • {app="orders"} | json — Pick the stream by label, then parse JSON.
  • count_over_time(...[5m]) — Count lines in 5 minutes, grouped by msg.
  • localhost:3001 — Grafana UI. Add Loki at http://loki:3100 as a data source.

Green output

$ curl -s localhost:3100/ready
ready
msg="db pool exhausted"       54
msg="upstream menu timeout"   26

Expected result. The tools change, the path stays: metric is red, open logs in the window, group, read the first one.

Verify: did it work?

  1. Alarm history

    aws cloudwatch describe-alarm-history --alarm-name orders-5xx --history-item-type StateUpdate --max-items 2 --query "AlarmHistoryItems[].HistorySummary"
    

    What it does: Shows OK to ALARM and back.

    Output

    [
        "Alarm updated from ALARM to OK",
        "Alarm updated from OK to ALARM"
    ]
    
  2. Metric value

    aws cloudwatch get-metric-statistics --namespace LogLab --metric-name Orders5xx --start-time $(date -u -d "-15 min" +%FT%TZ) --end-time $(date -u +%FT%TZ) --period 60 --statistics Sum --query "Datapoints[].Sum"
    

    What it does: Shows 80 in one minute.

    Output

    [
        80.0,
        0.0
    ]
    

When it is red 1

Alarm stays INSUFFICIENT_DATA

Cause. No datapoints because no matching lines arrived after the filter was made.

Fix, step by step

  1. Send new matching events.
  2. Set defaultValue=0 on the metric filter.
  3. Use --treat-missing-data notBreaching.

When it is red 2

Metric filter never counts JSON lines

Cause. The message is not valid JSON, or the field name is wrong.

Fix, step by step

  1. Look at one raw event in the console.
  2. Test the pattern: aws logs test-metric-filter --filter-pattern '{ $.status >= 500 }' --log-event-messages '{"status":500}'
  3. Fix the app or the pattern.

When it is red 3

No email arrives

Cause. The SNS subscription was not confirmed.

Fix, step by step

  1. aws sns list-subscriptions-by-topic --topic-arn ...
  2. If PendingConfirmation, click the link in the email.
  3. Set the alarm to ALARM again with set-alarm-state for a test.

Cleanup

  1. Delete lab alarm, filter and topic

    aws cloudwatch delete-alarms --alarm-names orders-5xx ; aws logs delete-metric-filter --log-group-name /loglab/orders --filter-name http5xx ; aws sns delete-topic --topic-arn arn:aws:sns:ap-south-1:111122223333:loglab-alerts ; docker rm -f loki grafana
    

    What it does: Removes lab pieces.

    Output

    loki
    grafana
    

Ravindra Bagale's Tip

When an alarm fires, do not panic. Take a time window, group the errors, read the first error.

Practice tasks

Easy Add a runbook link

Why: The person woken up needs steps.

What to do: Put the runbook URL in --alarm-description.

How:
  1. Edit the alarm.

Check: The email shows the link.

Medium Test without real errors

Why: Check the pipe safely.

What to do: Use set-alarm-state to force ALARM.

How:
  1. aws cloudwatch set-alarm-state --alarm-name orders-5xx --state-value ALARM --state-reason test

Check: Email arrives.

Hard Dashboard with logs

Why: One screen for on-call.

What to do: Make a CloudWatch dashboard with the metric and a Logs Insights widget.

How:
  1. Add the orders-5xx-top query as a widget.

Check: Graph and top errors on one page.

Easy Say alarm to log drill down in two lines

Why: If you can say it simply, you understand it. Juniors and interviewers both want the short version first.

What to do: Write two short lines about alarm to log drill down for a fresher who knows only Linux, Git and Docker basics.

How:
  1. Write the problem it solves.
  2. Write the one command or config line you use for it.
  3. Read it aloud to a friend.

Check: A fresher understands it without asking a question.

Easy Keep a throwaway log lab

Why: Practice needs a lab you can break. If it gets messy, you delete the containers and start again.

What to do: Run a small app in Docker that prints logs every second.

How:
  1. docker run -d --name ticker busybox sh -c "while true; do date; sleep 1; done"
  2. docker logs -f ticker
  3. Press Ctrl+C, then docker rm -f ticker.

Check: You see one new time line every second.

Medium Do it on a second stack

Why: Logging ideas must work for Python, Node.js and Java. Only the library changes.

What to do: Repeat this lesson with a different language than the one you used first.

How:
  1. If you used Python, use Node.js or Spring Boot now.
  2. Keep the same field names: time, level, msg, request_id.
  3. Compare the two outputs side by side.

Check: Both apps print the same fields in the same shape.

Medium Break it on purpose

Why: You must know the red error by face. In a real outage there is no time to read slowly.

What to do: Cause one error from the "When it is red" part of this lesson and fix it.

How:
  1. Follow the error section.
  2. Copy the exact message into your notes.
  3. Write the fix in one line.

Check: You fixed it using only the steps, without searching the web.

Medium Write a one-page runbook

Why: At 2 a.m. nobody remembers log commands. A short page saves the on-call person.

What to do: Write a one-page runbook for this lesson.

How:
  1. Title, when to use, exact commands, how to check, how to undo.

Check: A teammate can follow it alone.

Hard Explain it like an interview

Why: Interviewers want real stories, not definitions.

What to do: Record a 60 second answer about this lesson.

How:
  1. Say the problem, the command you ran, the log line you found and the fix.

Check: Your answer has a real command and a real log line.

Hard Draw the flow top to bottom

Why: A drawing shows where a log line is born and where it ends up.

What to do: Draw this lesson as boxes from top to bottom.

How:
  1. Start at the user click, go through the app, the log driver or agent, and end at the place you search.

Check: Each box matches a real command or file in this lesson.

Homework: try at home

Try at home

At home, build the alarm for your own lab app, save the three queries, and time yourself from email to root cause.

Recap

  • Metrics say something is wrong; logs say why.
  • Metric filter plus alarm plus SNS gives alerts from logs.
  • Search the alarm window only.
  • Group by message, then read the first error.
  • Grafana with Prometheus and Loki follows the same path.

FAQ

Should every error alert?

No. Alert on rates that hurt users, not on single lines.

Metric filter or app metrics?

App metrics are better. Metric filters help when you cannot change the app.

How do I avoid alert noise?

Use a sensible threshold, evaluation periods and treat missing data well.

Can alarms go to Slack?

Yes, SNS to AWS Chatbot or a Lambda that posts to Slack.

What is a good time to root cause?

Under 15 minutes for known issues, with saved queries.

Interview questions

  1. An alarm fires for high 5xx. Walk me through it.

    Note the window, open logs for the service, filter 5xx, group by message, read the first error and its request id, follow it across services, then check recent deploys.

  2. How do you create an alert from logs in AWS?

    Metric filter on the log group, CloudWatch alarm on the metric, SNS topic for notification.

  3. Why is the first error important?

    Later errors are often side effects; the first shows the trigger.

  4. What is LogQL?

    Grafana Loki's query language, label selectors plus pipeline filters and range aggregations.

  5. How do you reduce mean time to resolve?

    Saved queries, runbook links in alarms, correlation ids, dashboards.

Quick quiz

Q1. What turns log lines into a metric?

A metric filter.

Q2. What sends the alarm to email?

SNS.

Q3. Why search only in the alarm window?

It is faster, cheaper and less noisy.

Q4. Which query finds the main error?

stats count(*) by msg.

Q5. Name the Grafana log query language.

LogQL.

Did you understand? Let us try it once more.

Ravi Sir's Cards for this lesson

मराठी cards