Ravindra BagaleCourses & study guides मराठी

Chapter 14: Logging and Light Observability

DevOps

14.11d Structured logging mini-example

Why: the problem

Suppose Netflix-scale traffic gives you one million log lines a minute. A line like "user 42 paid 499 in 3004 ms" is easy for people but hard for machines. To find all payments slower than 3000 ms, you must write a fragile regex. Structured logging fixes this. Each line is a JSON object with named fields: time, level, service, request_id, user_id, amount, ms. Now tools can filter ms over 3000 exactly, count by service, and build graphs without regex. Every modern stack has a JSON logger: python-json-logger or structlog for Python, pino for Node.js, and the built-in JSON format in Spring Boot. In this lesson you will make all three print the same fields.

What we will build

You will make Python, Node.js and Spring Boot print JSON logs with the same field names, run them in Docker, and query them with jq and CloudWatch Logs Insights without any regex.

What: every term in plain English

  • Structured log — A log line made of named fields, usually JSON.
  • JSON — Text format of key and value pairs, like {"level":"INFO"}.
  • Field — One named value in the log, like ms or request_id.
  • Schema — The agreed list of field names and types for the whole company.
  • ECS (Elastic Common Schema) — A public schema for log field names.
  • structlog — A Python library for structured logs.
  • pino — A fast JSON logger for Node.js.
  • Context fields — Fields added once and kept on every line, like service and request_id.
Agree on fields Python: install Node: install Spring Boot: set format Run all three Query with jq
Structured logs: same fields in every language to one query everywhere

How: step by step

  1. Agree on fields

    time, level, service, msg, request_id, user_id, ms
    

    What it does: Same names in every language.

    Output

    (team doc)
    
  2. Python: install

    pip install -q structlog
    

    What it does: The structured logger for Python.

    Output

    (no output)
    
  3. Node: install

    npm i pino
    

    What it does: The JSON logger for Node.js.

    Output

    added 1 package
    
  4. Spring Boot: set format

    Add logging.structured.format.console=ecs to application.properties
    

    What it does: Spring Boot 3.4+ prints JSON logs with no extra library.

    Output

    (file saved)
    
  5. Run all three

    python pay.py ; node cart.js ; java -jar orders.jar
    

    What it does: Each prints JSON lines.

    Output

    {"level":"info","service":"pay",...}
    
  6. Query with jq

    cat *.jsonl | jq -c 'select(.ms > 1000)'
    

    What it does: Exact filter on a number field.

    Output

    {"service":"pay","ms":3004,...}
    

Example 1: Python with structlog

Stack. Python 3, structlog

Goal. Python with structlog.

pay.py

import structlog, time

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="pay")

def pay(request_id, user_id, amount):
    start = time.time()
    rlog = log.bind(request_id=request_id, user_id=user_id)
    rlog.info("payment started", amount=amount)
    time.sleep(0.2)
    rlog.info("payment done", amount=amount, ms=int((time.time() - start) * 1000))

pay("a1b2c3", 42, 499)

What each line does

  • add_log_level — Adds "level".
  • TimeStamper(... utc=True, key="time") — Adds "time" in ISO UTC.
  • EventRenamer("msg") — Calls the message field msg, our agreed name.
  • JSONRenderer() — Prints each event as one JSON line.
  • bind(...) — Context fields: added once, kept on every next line.

Green output

{"service":"pay","request_id":"a1b2c3","user_id":42,"amount":499,"level":"info","time":"2026-10-25T08:00:00.101Z","msg":"payment started"}
{"service":"pay","request_id":"a1b2c3","user_id":42,"amount":499,"ms":201,"level":"info","time":"2026-10-25T08:00:00.302Z","msg":"payment done"}

Expected result. Every line has the same fields. No regex needed to read ms or user_id.

Example 2: Node

Stack. Node.js 20, pino

Goal. Node.js with pino and child loggers.

cart.js

const pino = require("pino");
const log = pino({
  base: { service: "cart" },
  messageKey: "msg",
  timestamp: pino.stdTimeFunctions.isoTime,
  formatters: { level: (label) => ({ level: label }) }
});

function addItem(requestId, userId, sku) {
  const rlog = log.child({ request_id: requestId, user_id: userId });
  const start = Date.now();
  rlog.info({ sku }, "item added");
  rlog.warn({ sku, ms: Date.now() - start + 1200 }, "price service slow");
}

addItem("a1b2c3", 42, "BIRYANI-1");

What each line does

  • base: { service: "cart" } — Service field on every line.
  • messageKey: "msg" — Same message field name as Python.
  • isoTime — Time as ISO text, not a number.
  • formatters.level — Prints level as "info", not 30.
  • log.child({...}) — Like bind in Python: context for this request.

Green output

{"level":"info","time":"2026-10-25T08:00:01.010Z","service":"cart","request_id":"a1b2c3","user_id":42,"sku":"BIRYANI-1","msg":"item added"}
{"level":"warn","time":"2026-10-25T08:00:01.011Z","service":"cart","request_id":"a1b2c3","user_id":42,"sku":"BIRYANI-1","ms":1201,"msg":"price service slow"}

Expected result. Same fields as Python. One query now works for both services.

Example 3: Spring Boot JSON logs and one query for all

Stack. Java 17, Spring Boot 3.4, SLF4J 2, CloudWatch Insights

Goal. Spring Boot JSON logs and one query for all.

application.properties

spring.application.name=orders
logging.structured.format.console=ecs

OrderController.java (part)

@GetMapping("/orders/{id}")
public String get(@PathVariable String id) {
    MDC.put("request_id", id + "-rq");
    log.atInfo().addKeyValue("ms", 87).log("order read");
    MDC.clear();
    return "ok";
}

One Logs Insights query for all three services

fields time, service, level, msg, ms
| filter ms > 1000 or level in ["warn", "ERROR", "error"]
| stats count(*) as slow_or_bad, avg(ms) as avg_ms by service
| sort slow_or_bad desc

What each line does

  • logging.structured.format.console=ecs — Spring Boot 3.4+ prints JSON in Elastic Common Schema.
  • MDC.put("request_id", ...) — Adds the field to every line on this thread.
  • atInfo().addKeyValue("ms", 87) — SLF4J 2 fluent API: add a typed field.
  • stats ... by service — Compare services by slow or bad lines, no regex.

Green output

{"@timestamp":"2026-10-25T08:00:02.200Z","log.level":"INFO","service.name":"orders","request_id":"991-rq","ms":"87","message":"order read"}

service   slow_or_bad   avg_ms
pay       3             2210
cart      1             1201
orders    0             87

Expected result. ECS uses its own names (log.level, message). Map them once in your schema doc, or use a logstash encoder with your own names.

Verify: did it work?

  1. Every line is JSON

    python pay.py | jq -e . > /dev/null && echo valid
    

    What it does: jq fails on any non-JSON line.

    Output

    valid
    
  2. Same keys in Python and Node

    python pay.py | jq -r "keys[]" | sort -u ; node cart.js | jq -r "keys[]" | sort -u
    

    What it does: Compare the key lists.

    Output

    level
    msg
    request_id
    service
    time
    user_id
    

When it is red 1

parse error: Invalid numeric literal at line 1, column 5

Cause. A plain text line got mixed in, like a banner from a library.

Fix, step by step

  1. Find it: grep -v "^{" app.log | head
  2. Route that library through the JSON logger, or turn its banner off.
  3. Run jq again.

When it is red 2

Fields have different names across services (msg vs message)

Cause. No shared schema.

Fix, step by step

  1. Write a one-page field list.
  2. Rename in each logger config (messageKey, EventRenamer).
  3. Or rename at the shipper with a Fluent Bit modify filter.

When it is red 3

ms is a string in some lines, so ms > 1000 fails

Cause. Some loggers write numbers as text.

Fix, step by step

  1. Log numbers as numbers in code.
  2. If old lines still have text values, filter on the new lines only.
  3. Retest the query.

Cleanup

  1. Remove lab files

    rm -f *.jsonl ; rm -rf node_modules
    

    What it does: Lab cleanup.

    Output

    (no output)
    

Ravindra Bagale's Tip

JSON logs are a language machines understand. Keep field names the same across all services.

Practice tasks

Easy Add a version field

Why: Know which release logged it.

What to do: Add version="1.4.2" with bind or base.

How:
  1. log.bind(version="1.4.2")

Check: Every line shows version.

Medium Pretty print in dev only

Why: JSON is hard to read on a laptop.

What to do: Use pino-pretty or structlog ConsoleRenderer in dev.

How:
  1. node cart.js | npx pino-pretty

Check: Colour lines in dev, JSON in prod.

Hard Ship to Loki with labels

Why: Low label count is key.

What to do: Send JSON logs to Loki with labels app and env only.

How:
  1. Keep request_id as a field, not a label.

Check: Queries are fast and labels stay few.

Easy Say structured logging 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 structured logging 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, write a field list for your team and make two apps in two languages follow it. Prove it with jq keys.

Recap

  • Structured logs are JSON lines with named fields.
  • structlog, pino and Spring Boot ECS make it easy.
  • Agree on one schema for all services.
  • Context fields like request_id go on every line.
  • Queries become exact and regex-free.

FAQ

Is JSON harder to read?

A bit for people, much easier for tools. Use a pretty printer in dev.

Does JSON cost more?

Slightly bigger lines. The time saved is worth it.

Which schema should I use?

Your own short list, or ECS or OpenTelemetry semantic names.

Can old text logs be parsed?

Yes, with parse in Insights or a parser in Fluent Bit, but it is fragile.

Should user_id be a Loki label?

No. High-cardinality values stay fields, not labels.

Interview questions

  1. What is structured logging and why?

    Logs as key-value data, usually JSON, so tools can filter, aggregate and alert exactly without regex.

  2. How do you do it in Python, Node and Java?

    structlog or python-json-logger; pino; Spring Boot structured logging or logstash-logback-encoder with MDC.

  3. What are context fields?

    Fields bound once (service, request_id) and included automatically on every line.

  4. How do you keep logs consistent across teams?

    A shared schema, shared logging library and review checks.

  5. What is cardinality and why care?

    The number of unique values; high-cardinality fields as labels make Loki or metrics slow and costly.

Quick quiz

Q1. What is a structured log?

A log line with named fields, usually JSON.

Q2. Python library used here?

structlog.

Q3. Node library used here?

pino.

Q4. Spring Boot setting for JSON?

logging.structured.format.console=ecs.

Q5. Why the same field names?

So one query works across all services.

Did you understand? Let us try it once more.

Ravi Sir's Cards for this lesson

मराठी cards