Ravindra BagaleCourses & study guides मराठी

Chapter 14: Logging and Light Observability

DevOps

14.10 Anti-patterns

Why: the problem

Suppose a startup's app logs "error occurred" with no time, no id and no detail. Another service logs every SQL query at DEBUG in production, and the CloudWatch bill jumps to 4 lakh rupees a month. A third service writes logs into a file inside its container, and when the pod restarts, the evidence is gone. A fourth catches every exception and logs nothing. These are logging anti-patterns, bad habits that look harmless until the night of an outage. Every team at Flipkart, Swiggy or Infosys has met them. In this lesson we look at each bad habit next to its fix, in real code, so you can spot them in code review.

What we will build

You will take a badly logged Python service, find seven anti-patterns, fix them one by one, do the same for a Java and a Node.js snippet, and add a simple log review checklist to your pull request template.

What: every term in plain English

  • Anti-pattern — A common habit that looks fine but causes trouble later.
  • Swallowed exception — An error caught and ignored, with no log line.
  • Log spam — Too many useless lines, so real errors are hidden and cost goes up.
  • Vague message — A line like "error" that says nothing useful.
  • Log and throw — Logging an error and also re-throwing it, so it is logged twice or more.
  • String building cost — Building big log text even when the level is off.
  • Sampling — Keeping only some of many similar lines, like 1 in 100.
  • Code review checklist — A short list reviewers check for every change.
Count lines per minute Find the top repeated lines Find vague errors Find swallowed exceptions in code Set the right level Measure again
Anti-patterns: noisy, vague, swallowed, leaky to clean one line per event

How: step by step

  1. Count lines per minute

    docker logs --since 1m api 2>&1 | wc -l
    

    What it does: Too many lines per minute is a smell.

    Output

    48210
    
  2. Find the top repeated lines

    docker logs --since 5m api 2>&1 | cut -c 25- | sort | uniq -c | sort -rn | head -n 3
    

    What it does: Shows the noisiest messages.

    Output

    91022 DEBUG SELECT * FROM menu WHERE id=?
      410 INFO health ok
        3 ERROR error
    
  3. Find vague errors

    docker logs api 2>&1 | grep -E "ERROR (error|failed|exception)$"
    

    What it does: Lines that say nothing.

    Output

    2026-10-25 12:00:01 ERROR error
    
  4. Find swallowed exceptions in code

    grep -rn -A 1 "except Exception" src/ | grep -E "pass|continue"
    

    What it does: Catches with no log.

    Output

    src/pay.py-42-        pass
    
  5. Set the right level

    export LOG_LEVEL=INFO && docker compose up -d api
    

    What it does: Turn DEBUG off in production.

    Output

    Container api Recreated
    
  6. Measure again

    docker logs --since 1m api 2>&1 | wc -l
    

    What it does: Lines per minute fall a lot.

    Output

    612
    

Example 1: Python: seven bad habits fixed

Stack. Python 3, logging

Goal. Python: seven bad habits fixed.

bad.py

import logging
log = logging.getLogger()
def pay(order, card):
    print("paying")                             # 1 print, no level or time
    log.debug("order data: " + str(order))      # 2 builds text always
    try:
        charge(card)
    except Exception:
        pass                                    # 3 swallowed
    log.info("card " + card)                    # 4 secret in log
    log.error("error")                          # 5 vague
    for item in order["items"]:
        log.info("item ok")                     # 6 spam in a loop

good.py

import logging
log = logging.getLogger("pay")                  # named logger
def pay(order, card):
    log.debug("order data: %s", order)          # lazy: built only if DEBUG on
    try:
        charge(card)
    except TimeoutError:
        log.exception("charge timeout order=%s gateway=razorpay", order["id"])
        raise                                   # log once, then let caller decide
    log.info("charge ok order=%s last4=%s items=%d",
             order["id"], card[-4:], len(order["items"]))

What each line does

  • print(...) — Use the logger: it adds time, level and goes to the right place.
  • "..." + str(order) — Use %s args: no cost when DEBUG is off.
  • except: pass — Never hide errors. Log with context, then raise or handle.
  • "card " + card — Log only last4.
  • log.error("error") — Say what failed, for which id, against which system.
  • log in a loop — One summary line with a count.

Green output

bad.py output:
paying
2026-10-25 12:00:01 INFO card 4111111111111111
2026-10-25 12:00:01 ERROR error
2026-10-25 12:00:01 INFO item ok
2026-10-25 12:00:01 INFO item ok
good.py output:
2026-10-25 12:00:01 INFO charge ok order=991 last4=1111 items=2

Expected result. One clear line replaced five noisy, risky lines.

Example 2: Java: log and throw, and the guard

Stack. Java 17, Spring Boot, log4j2

Goal. Java: log and throw, and the guard.

Bad.java

try {
    repo.save(order);
} catch (SQLException e) {
    log.error("save failed", e);
    throw new RuntimeException(e);   // caller logs it again, and again
}
log.debug("order " + order.toJson());  // toJson runs even when DEBUG is off

Good.java

try {
    repo.save(order);
} catch (SQLException e) {
    throw new OrderSaveException("save failed order=" + order.getId(), e); // no log here
}
// one global handler logs it once with the stack trace
log.debug("order {}", order::toJson);  // lambda: runs only if DEBUG is on (log4j2)

What each line does

  • log.error + throw — The same error appears 3 times in the logs. Pick one place to log.
  • new OrderSaveException(..., e) — Wrap with context and keep the cause.
  • global handler — One @ControllerAdvice or filter logs all unhandled errors once.
  • order::toJson — Supplier: expensive work only when needed.

Green output

Before: 3 copies of the same SQLException stack trace per failed order
After:
2026-10-25T12:05:01Z ERROR c.s.o.GlobalHandler - OrderSaveException: save failed order=991
Caused by: java.sql.SQLTransientConnectionException: HikariPool-1 - Connection is not available

Expected result. One error, one stack trace, with the order id and the real cause.

Example 3: Node

Stack. Node.js, team process

Goal. Node.js: sampling noisy lines and a PR checklist.

sample.js

let n = 0;
function healthOk() {
  n += 1;
  if (n % 100 === 0) {
    console.log(JSON.stringify({ level: "info", msg: "health ok", count: n }));
  }
}
setInterval(healthOk, 10);

PULL_REQUEST_TEMPLATE.md (logging part)

Logging checklist
[ ] No print or console.log for real events, the logger is used
[ ] Errors are logged once, with ids and the cause
[ ] No secrets, tokens, CVV, full card or Aadhaar numbers
[ ] No log line inside a hot loop
[ ] Level is right: DEBUG for detail, INFO for events, ERROR for failures
[ ] New fields use the agreed names: request_id, order_id, user_id

What each line does

  • n % 100 === 0 — Log only 1 in 100 health checks.
  • count: n — Keep the total so the number stays true.
  • Checklist — Reviewers tick it on every pull request.

Green output

$ node sample.js
{"level":"info","msg":"health ok","count":100}
{"level":"info","msg":"health ok","count":200}

Expected result. 100 times fewer lines, and you still know the health check runs.

Verify: did it work?

  1. Lines per minute after fixes

    docker logs --since 1m api 2>&1 | wc -l
    

    What it does: Should be much lower.

    Output

    612
    
  2. No vague errors left

    docker logs --since 1h api 2>&1 | grep -c -E "ERROR (error|failed)$"
    

    What it does: Should be 0.

    Output

    0
    

When it is red 1

After lazy logging: TypeError: not all arguments converted during string formatting

Cause. Number of %s does not match the arguments.

Fix, step by step

  1. Count %s in the message.
  2. Pass the same number of args.
  3. Run the test again.

When it is red 2

The bill stays high after setting INFO

Cause. A library still logs DEBUG on its own logger.

Fix, step by step

  1. logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
  2. Rebuild and check lines per minute.

When it is red 3

Errors vanished from logs after the fix

Cause. You removed the log but no global handler logs it.

Fix, step by step

  1. Add a global error handler that logs unhandled errors.
  2. Throw a test error.
  3. Check it appears exactly once.

Cleanup

  1. Reset the env

    unset LOG_LEVEL
    

    What it does: Back to defaults.

    Output

    (no output)
    

Ravindra Bagale's Tip

Do not write a log that only says error. Say what failed, which order, which system.

Practice tasks

Easy Rewrite a vague line

Why: Practice clear messages.

What to do: Change "error" to a useful line.

How:
  1. Add what, which id, which system.

Check: "charge timeout order=991 gateway=razorpay".

Medium Find the noisiest logger

Why: Cost comes from a few loggers.

What to do: Use Logs Insights stats count(*) by logger.

How:
  1. stats count(*) as n by logger | sort n desc | limit 5

Check: You find one logger with most lines.

Hard Add a lint rule

Why: Stop print in code.

What to do: Add a flake8 or eslint rule that blocks print or console.log.

How:
  1. eslint no-console: error

Check: CI fails when someone uses console.log.

Easy Say logging anti-patterns 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 logging anti-patterns 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, open one of your old projects, find three logging anti-patterns from this lesson, and fix them.

Recap

  • Do not use print for real events.
  • Never swallow exceptions.
  • Log once, with ids and cause.
  • No loops, no spam, sample if needed.
  • Use INFO in production and lazy arguments.

FAQ

Is DEBUG ever OK in production?

For a short time on one service to debug, then turn it off.

Where should I log an error, low or high in the code?

Once, at the place that handles it, often a global handler.

Are health check logs useful?

Rarely. Sample them or turn them off.

Does logging slow the app?

Heavy logging does. Lazy args and right levels keep it fast.

How do I convince my team?

Show the cost and the time lost in the last incident.

Interview questions

  1. Name some logging anti-patterns.

    print statements, swallowed exceptions, vague messages, log-and-throw, secrets in logs, logging in loops, DEBUG in production.

  2. How do you reduce log volume and cost?

    Right levels, sampling, removing noisy lines, retention and filtering at the shipper.

  3. Why is log-and-throw bad?

    It duplicates the same error many times and confuses incident analysis.

  4. What makes a good error log line?

    What failed, ids, dependency name, cause and the stack trace, logged once.

  5. How do you enforce logging standards?

    Shared logging library, PR checklist, linters and log reviews after incidents.

Quick quiz

Q1. What is a swallowed exception?

An error caught and ignored with no log.

Q2. Why use %s args instead of +?

The text is built only if the level is on.

Q3. What is log and throw?

Logging and re-throwing, so the error appears many times.

Q4. How do you handle noisy repeated lines?

Sampling or one summary line with a count.

Q5. Which level for production?

INFO, with DEBUG only for short debugging.

Did you understand? Let us try it once more.

Ravi Sir's Cards for this lesson

मराठी cards