Ravindra BagaleCourses & study guides मराठी

Chapter 14: Logging and Light Observability

DevOps

14.12 Lab — generate, query, write the note

Why: the problem

Now we put the whole chapter together, like a real on-call day at a Swiggy-like company. You will run a small app in Docker that writes JSON logs with request ids. You will ship the logs to CloudWatch. You will make an alarm from the logs. You will cause a failure on purpose. Then you will find the root cause from the logs and write a short incident note, just like engineers do after every outage. This lab is the proof that you can do logging in practice, not only in theory. Interviewers love it when you can tell this exact story with real commands.

What we will build

You will build a Flask order API with structured JSON logs and request ids, run it with Docker Compose using the awslogs driver and size limits, add a metric filter and an alarm, break the database setting on purpose, find the cause with Logs Insights, and write a five-line incident note.

What: every term in plain English

  • Lab — A safe practice setup you can break and delete.
  • Incident — A time when users are hurt, like checkout failing.
  • Incident note — A short write-up: what happened, impact, cause, fix, next steps.
  • Root cause — The real reason, not the side effect.
  • Blameless — Talk about systems and steps, not about blaming a person.
  • Time to detect — From the problem start to the alert.
  • Time to resolve — From the alert to the fix.
  • Saved query — A Logs Insights query saved for reuse in incidents.
Create the folder Write app.py and compose.yaml Start it Send traffic Break it on purpose Send traffic again and watch
Final lab: app logs JSON to CloudWatch to alarm to query to note

How: step by step

  1. Create the folder

    mkdir -p ~/loglab/final && cd ~/loglab/final
    

    What it does: All final lab files go here.

    Output

    (no output)
    
  2. Write app.py and compose.yaml

    Copy Example 1 and Example 2
    

    What it does: The app and how it runs.

    Output

    (files saved)
    
  3. Start it

    docker compose up -d --build
    

    What it does: Builds the image and starts the API.

    Output

    Container final-api-1  Started
    
  4. Send traffic

    for i in $(seq 1 20); do curl -s localhost:8080/orders/$i -o /dev/null; done
    

    What it does: 20 good requests.

    Output

    (no output)
    
  5. Break it on purpose

    DB_TIMEOUT_MS=1 docker compose up -d
    

    What it does: The app now fails most DB calls.

    Output

    Container final-api-1  Recreated
    
  6. Send traffic again and watch

    for i in $(seq 1 80); do curl -s localhost:8080/orders/$i -o /dev/null; done; aws logs tail /loglab/final --since 5m --filter-pattern ERROR --format short | tail -n 2
    

    What it does: Errors appear in CloudWatch.

    Output

    08:31:20 api-1 {"level":"error","msg":"db timeout","timeout_ms":1,...}
    

Example 1: The order API with structured logs and request ids

Stack. Python 3.12, Flask, structlog, Docker

Goal. The order API with structured logs and request ids.

app.py

import os, time, uuid, random, structlog
from flask import Flask, request, g

structlog.configure(processors=[
    structlog.processors.add_log_level,
    structlog.processors.TimeStamper(fmt="iso", utc=True, key="time"),
    structlog.processors.EventRenamer("msg"),
    structlog.processors.JSONRenderer(),
])
log = structlog.get_logger().bind(service="orders", version=os.getenv("VERSION", "1.0"))
TIMEOUT = int(os.getenv("DB_TIMEOUT_MS", "500"))
app = Flask(__name__)

@app.before_request
def start():
    g.rid = request.headers.get("X-Request-ID") or uuid.uuid4().hex
    g.t0 = time.time()

@app.route("/orders/<oid>")
def order(oid):
    db_ms = random.randint(5, 40)
    ms = lambda: int((time.time() - g.t0) * 1000)
    if db_ms > TIMEOUT:
        log.error("db timeout", request_id=g.rid, order_id=oid, timeout_ms=TIMEOUT, status=500, ms=ms())
        return {"error": "try again", "request_id": g.rid}, 500
    log.info("order read", request_id=g.rid, order_id=oid, status=200, ms=ms())
    return {"order": oid}

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8080)

requirements.txt

flask==3.0.3
structlog==24.4.0

Dockerfile

FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app.py .
ENV PYTHONUNBUFFERED=1
USER nobody
CMD ["python", "app.py"]

What each line does

  • structlog JSONRenderer — JSON lines with time, level, msg.
  • bind(service, version) — Every line says which service and release.
  • DB_TIMEOUT_MS — Our break switch. 1 ms makes almost every call fail.
  • request_id in every line and in the error body — Users and support can quote it.
  • USER nobody — Do not run as root.
  • PYTHONUNBUFFERED=1 — Lines reach Docker at once.

Green output

$ docker compose logs api --tail 2
api-1  | {"service":"orders","version":"1.0","request_id":"3e1f...","order_id":"19","status":200,"ms":2,"level":"info","time":"2026-10-25T08:30:10.101Z","msg":"order read"}
api-1  | {"service":"orders","version":"1.0","request_id":"9a7c...","order_id":"20","status":200,"ms":1,"level":"info","time":"2026-10-25T08:30:10.140Z","msg":"order read"}

Expected result. Clean JSON lines with all the fields we need for search and alarms.

Example 2: Compose with awslogs and the metric filter plus alarm

Stack. Docker Compose, CloudWatch Logs, alarms, SNS

Goal. Compose with awslogs and the metric filter plus alarm.

compose.yaml

services:
  api:
    build: .
    ports:
      - "8080:8080"
    environment:
      VERSION: "1.0"
      DB_TIMEOUT_MS: "${DB_TIMEOUT_MS:-500}"
    logging:
      driver: awslogs
      options:
        awslogs-region: ap-south-1
        awslogs-group: /loglab/final
        awslogs-stream: api-1
        awslogs-create-group: "true"

alerts.sh

aws logs put-retention-policy --log-group-name /loglab/final --retention-in-days 7
aws logs put-metric-filter --log-group-name /loglab/final --filter-name final5xx \
  --filter-pattern '{ $.status = 500 }' \
  --metric-transformations metricName=Final5xx,metricNamespace=LogLab,metricValue=1,defaultValue=0
aws cloudwatch put-metric-alarm --alarm-name final-5xx --namespace LogLab --metric-name Final5xx \
  --statistic Sum --period 60 --evaluation-periods 1 --threshold 20 \
  --comparison-operator GreaterThanThreshold --treat-missing-data notBreaching \
  --alarm-actions arn:aws:sns:ap-south-1:111122223333:loglab-alerts

What each line does

  • driver: awslogs — Logs go straight to CloudWatch. Run this lab on EC2 with an instance role.
  • ${DB_TIMEOUT_MS:-500} — Use 500 unless we set the break value.
  • retention 7 days — Lab logs do not live forever.
  • metric filter on $.status = 500 — Counts failures from the JSON logs.
  • alarm threshold 20 per minute — Fires when failures spike.

Green output

$ bash alerts.sh
$ aws cloudwatch describe-alarms --alarm-names final-5xx --query "MetricAlarms[0].StateValue"
"ALARM"

Expected result. After the break, the alarm fires within about a minute, and the email arrives.

Example 3: Find the root cause and write the incident note

Stack. CloudWatch Logs Insights, incident practice

Goal. Find the root cause and write the incident note.

Logs Insights (group /loglab/final, last 15 min)

filter status = 500
| stats count(*) as n, min(time) as first_seen by msg, timeout_ms, version
| sort n desc

incident-note.md

Incident: orders API 5xx spike, 25 Oct 2026, 14:01-14:06 IST
Impact:   about 75 of 80 order reads failed for 5 minutes
Detect:   alarm final-5xx fired at 14:02 IST (time to detect 1 min)
Cause:    DB_TIMEOUT_MS changed from 500 to 1 in the last deploy (logs show timeout_ms=1)
Fix:      rolled back to DB_TIMEOUT_MS=500 at 14:06 IST (time to resolve 4 min)
Next:     validate config values in CI; add timeout_ms to the deploy checklist

What each line does

  • stats ... by msg, timeout_ms, version — Group errors by what they say and by the config value. The odd value jumps out.
  • min(time) as first_seen — When it started.
  • Incident note — Five short lines: what, impact, detect, cause, fix, next.
  • Blameless wording — We say the config changed, not who changed it.

Green output

msg          timeout_ms   version   n    first_seen
db timeout   1            1.0       75   2026-10-25T08:31:02.110Z

$ docker compose up -d   (DB_TIMEOUT_MS back to default 500)
$ aws cloudwatch describe-alarms --alarm-names final-5xx --query "MetricAlarms[0].StateValue"
"OK"

Expected result. The log field timeout_ms=1 proves the cause. After the rollback the alarm goes back to OK.

Verify: did it work?

  1. App healthy again

    curl -s -o /dev/null -w "%{http_code}" localhost:8080/orders/1
    

    What it does: Should be 200.

    Output

    200
    
  2. No new errors

    aws logs tail /loglab/final --since 2m --filter-pattern ERROR | wc -l
    

    What it does: Should be 0.

    Output

    0
    

When it is red 1

Error response from daemon: failed to initialize logging driver: failed to create Cloudwatch log stream: NoCredentialProviders

Cause. Docker cannot find AWS credentials on this machine.

Fix, step by step

  1. Run the lab on an EC2 instance with an IAM role that can write logs.
  2. Or switch the driver to json-file for a local-only run.
  3. docker compose up -d again.

When it is red 2

curl: (7) Failed to connect to localhost port 8080

Cause. The container exited, often a Python error at start.

Fix, step by step

  1. docker compose ps -a
  2. docker compose logs api (works with json-file) or check CloudWatch.
  3. Fix the error, rebuild with --build.

When it is red 3

Alarm never fires

Cause. Fewer than 20 errors in one minute, or the filter does not match.

Fix, step by step

  1. Send more traffic in one minute.
  2. Test the filter with aws logs test-metric-filter.
  3. Check defaultValue=0 and the namespace.

Cleanup

  1. Tear down the whole lab

    docker compose down --rmi local ; aws cloudwatch delete-alarms --alarm-names final-5xx ; aws logs delete-log-group --log-group-name /loglab/final
    

    What it does: Removes containers, image, alarm and logs.

    Output

    Container final-api-1  Removed
    

Ravindra Bagale's Tip

Do this lab yourself. Tell the full story in an interview and they will see you are practical.

Practice tasks

Easy Add a version bump

Why: See releases in logs.

What to do: Set VERSION=1.1 and redeploy.

How:
  1. VERSION=1.1 docker compose up -d

Check: New lines show version 1.1.

Medium Add nginx in front

Why: Two log sources, one id.

What to do: Add nginx to Compose and pass X-Request-ID.

How:
  1. proxy_set_header X-Request-ID $request_id;

Check: One id in nginx and app logs.

Hard Do the lab with Loki

Why: Learn a second stack.

What to do: Replace awslogs with the Loki Docker driver and use LogQL.

How:
  1. docker plugin install grafana/loki-docker-driver:latest --alias loki --grant-all-permissions

Check: Same root cause found in Grafana.

Easy Say the full logging lab 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 the full logging lab 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, repeat the full lab with a Node.js pino app instead of Python, break a different setting, and write your own incident note.

Recap

  • A real lab ties all lessons together.
  • JSON logs with request ids make search exact.
  • awslogs ships, retention limits, metric filter plus alarm alerts.
  • Logs Insights grouped by config field shows the cause.
  • A short blameless incident note closes the loop.

FAQ

Can I do this lab without AWS?

Yes. Use json-file and jq, or Loki and Grafana in Docker.

Will this lab cost money?

A few rupees at most if you delete it the same day.

Why break it on purpose?

So you learn the red path calmly before a real incident.

How long should an incident note be?

Short. Five to ten lines is enough for most cases.

What should I tell in interviews?

This exact story: app, logs, alarm, query, cause, fix, note.

Interview questions

  1. Walk me through how you would set up logging for a new service.

    JSON logs to stdout with request ids, a driver or agent to a central store, retention, masking, metric filters and alarms, saved queries and a runbook.

  2. Tell me about an incident you debugged with logs.

    Use this lab: 5xx alarm, grouped errors showed timeout_ms=1 after a deploy, rolled back in 4 minutes, added config checks in CI.

  3. What is in a good post-incident note?

    Timeline, impact, detection, root cause, fix and action items, blameless.

  4. How do you test that alerts work?

    Break things in a lab or use set-alarm-state, then confirm the notification arrives.

  5. What would you improve next?

    Add traces with OpenTelemetry and a dashboard combining metrics and top errors.

Quick quiz

Q1. Which field proved the root cause?

timeout_ms=1.

Q2. Which driver sent logs to CloudWatch?

awslogs.

Q3. What counted the 500s?

A metric filter on $.status = 500.

Q4. What are the parts of an incident note?

What, impact, detect, cause, fix, next.

Q5. Why blameless notes?

So people share facts openly and the system gets fixed.

Lab

Practise the CloudWatch Logs primary path (or stdout + documented ship step if your account setup blocks agents today — still write the incident note).

  1. Run badge API hello API (or any tiny app) that writes an ERROR line on a deliberate bad request.
  2. Capture logs with docker logs and (when available) ship/query via CloudWatch Logs in your lab account.
  3. Create or use a clearly named lab log group; confirm events appear.
  4. Query/filter the last ERROR; copy one line.
  5. Write a five-line incident note (When, Symptom, Evidence, Action, Follow-up) in your notebook or private README — no real secrets, no customer PII.
  6. Add one sentence on how a correlation id would make the search easier.
  7. Optional interview prep: three bullets comparing CloudWatch Logs vs ELK at idea level (store, search, ops ownership) — no invented product limits.

Practice task

Redact this bad log line into a safe version: ERROR user=priya token=AKIAexample secret=hunter2 order=55 failed (Use obviously fake placeholders only — never paste real credentials into notes you might commit.)

Thodkyaat sangaycha tar

  • Logs are CCTV: metrics detect; logs explain.
  • Containers: prefer stdout/stderr; use docker logs / Compose logs.
  • journald + logrotate keep hosts healthy; link AWS Linux chapters for depth.
  • Primary path: CloudWatch Logs (groups/streams/search); ELK is the common alternate idea — do not dual-build both in this lab.
  • Correlation ids tie one request across lines; never log secrets.
  • Close incidents with a short note: when, symptom, evidence, action, follow-up.

Did you understand? Let us try it once more.

Ravi Sir's Cards for this lesson

मराठी cards