Ravindra BagaleCourses & study guides मराठी

Chapter 14: Logging and Light Observability

DevOps

14.1 Why logs — flight recorder for the server

Why: the problem

Suppose you order biryani on Swiggy at 9 p.m. You tap Pay. The app spins and then says "Something went wrong". You are angry. On the server side, an engineer gets an alert. She has one question: what exactly happened at 9:00:14 p.m. for this order? She cannot see your phone. She cannot replay the night. She has only one thing: the log lines the servers wrote at that moment. A log is like the black box in an aeroplane. It records what the system did, step by step, with time. If the app writes good logs, she finds the error in two minutes. If the app writes nothing, or writes junk, she guesses for two hours. That is why every DevOps engineer must know where logs are born, where they go, and how to search them.

What we will build

You will run a tiny Python web app that writes log lines. You will make one request succeed and one request fail. Then you will read the logs and find the failing request by its time and its error line. Next you will do the same with a Node.js app and an nginx web server, so you see that every stack writes logs in a similar way.

What: every term in plain English

  • Log — A line of text a program writes to say what it did, with the time.
  • Log level — How serious the line is: DEBUG, INFO, WARNING, ERROR, CRITICAL.
  • Timestamp — The date and time at the start of the line. Always use UTC or show the zone.
  • Event — One thing that happened, like "payment failed for order 991".
  • Stack trace — The list of code lines the program was in when it crashed. It shows where the bug is.
  • stdout — Standard output. The normal place a program prints text.
  • stderr — Standard error. The place a program prints error text.
  • Flight recorder — Our simple picture: logs record everything so we can replay a bad night later.
Make a lab folder Check Python Create a virtual env Install Flask Run the app from Example 1 Send one good and one bad request
Why logs: event to log line to search to fix

How: step by step

  1. Make a lab folder

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

    What it does: All files for this chapter live here.

    Output

    (no output)
    
  2. Check Python

    python3 --version
    

    What it does: We need Python 3.8 or newer.

    Output

    Python 3.12.3
    
  3. Create a virtual env

    python3 -m venv .venv && . .venv/bin/activate
    

    What it does: A private Python just for this lab.

    Output

    (.venv) ravi@lab:~/loglab$
    
  4. Install Flask

    pip install -q flask
    

    What it does: Flask is a small Python web framework.

    Output

    (no output)
    
  5. Run the app from Example 1

    python app.py
    

    What it does: The app starts on port 5000 and prints its first log line.

    Output

    INFO  app started on port 5000
    
  6. Send one good and one bad request

    curl -s localhost:5000/pay?order=101 ; curl -s localhost:5000/pay?order=0
    

    What it does: The first works. The second makes the app log an error.

    Output

    paid 101
    failed
    

Example 1: A Python app that writes useful log lines

Stack. Python 3, Flask, logging module

Goal. A Python app that writes useful log lines.

app.py

import logging
from flask import Flask, request

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s %(levelname)-5s %(message)s",
)
log = logging.getLogger("pay")
app = Flask(__name__)

@app.route("/pay")
def pay():
    order = request.args.get("order", "0")
    log.info("payment started order=%s", order)
    try:
        if order == "0":
            raise ValueError("order id is zero")
        log.info("payment ok order=%s", order)
        return "paid " + order
    except Exception:
        log.exception("payment failed order=%s", order)
        return "failed", 500

if __name__ == "__main__":
    log.info("app started on port 5000")
    app.run(port=5000)

What each line does

  • logging.basicConfig(...) — Sets up logging once for the whole app.
  • level=logging.INFO — Show INFO and above. DEBUG lines are hidden.
  • format="%(asctime)s ..." — Each line starts with time, then level, then message.
  • log.info(...) — Writes a normal event line.
  • log.exception(...) — Writes an ERROR line plus the full stack trace.
  • return "failed", 500 — Sends HTTP 500 so monitoring also sees the failure.

Green output

2026-10-25 09:00:01,120 INFO  app started on port 5000
2026-10-25 09:00:14,402 INFO  payment started order=101
2026-10-25 09:00:14,403 INFO  payment ok order=101
2026-10-25 09:00:20,511 INFO  payment started order=0
2026-10-25 09:00:20,512 ERROR payment failed order=0
Traceback (most recent call last):
  File "/home/ravi/loglab/app.py", line 17, in pay
    raise ValueError("order id is zero")
ValueError: order id is zero

Expected result. You can see the exact time, the order id and the code line (line 17) that failed. That is a useful log.

Example 2: The same idea in Node

Stack. Node.js 20, http module

Goal. The same idea in Node.js.

server.js

const http = require("http");

function log(level, msg) {
  console.log(new Date().toISOString() + " " + level + " " + msg);
}

http.createServer((req, res) => {
  log("INFO", "request " + req.method + " " + req.url);
  if (req.url.startsWith("/fail")) {
    console.error(new Date().toISOString() + " ERROR db timeout after 3000ms");
    res.statusCode = 500;
    return res.end("failed");
  }
  res.end("ok");
}).listen(3000, () => log("INFO", "listening on 3000"));

What each line does

  • console.log(...) — Writes to stdout. Use it for normal events.
  • console.error(...) — Writes to stderr. Use it for errors.
  • new Date().toISOString() — Time in UTC, like 2026-10-25T03:30:14.402Z.
  • res.statusCode = 500 — The client and monitoring both see a failure.

Green output

$ node server.js
2026-10-25T03:30:01.010Z INFO listening on 3000
$ curl -s localhost:3000/ ; curl -s localhost:3000/fail
2026-10-25T03:30:14.402Z INFO request GET /
2026-10-25T03:30:20.511Z INFO request GET /fail
2026-10-25T03:30:20.512Z ERROR db timeout after 3000ms

Expected result. Node prints the same shape: time, level, message. Errors go to stderr.

Example 3: nginx access and error logs on Ubuntu

Stack. Ubuntu 24.04, nginx

Goal. nginx access and error logs on Ubuntu.

Commands

sudo apt-get update && sudo apt-get install -y nginx
curl -s -o /dev/null -w "%{http_code}" localhost/
curl -s -o /dev/null -w "%{http_code}" localhost/missing.html
sudo tail -n 2 /var/log/nginx/access.log
sudo tail -n 2 /var/log/nginx/error.log

What each line does

  • apt-get install -y nginx — Installs the nginx web server.
  • -w "%{http_code}" — curl prints only the HTTP status code.
  • /var/log/nginx/access.log — One line per request: IP, time, path, status, size.
  • /var/log/nginx/error.log — Problems nginx itself hit, like a missing file.

Green output

200
404
127.0.0.1 - - [25/Oct/2026:09:05:01 +0530] "GET / HTTP/1.1" 200 615 "-" "curl/8.5.0"
127.0.0.1 - - [25/Oct/2026:09:05:03 +0530] "GET /missing.html HTTP/1.1" 404 153 "-" "curl/8.5.0"
2026/10/25 09:05:03 [error] 2140#2140: *2 open() "/var/www/html/missing.html" failed (2: No such file or directory)

Expected result. The access log shows the 404. The error log shows why: the file is not there.

Verify: did it work?

  1. Count the error lines

    python app.py 2>&1 | tee app.log  (in one terminal), then: grep -c ERROR app.log
    

    What it does: We saved the logs to a file and counted errors.

    Output

    1
    
  2. Find the order that failed

    grep "payment failed" app.log
    

    What it does: Shows the full error line with order id.

    Output

    2026-10-25 09:00:20,512 ERROR payment failed order=0
    

When it is red 1

No log lines appear at all

Cause. The level is too high, for example WARNING, so INFO lines are hidden.

Fix, step by step

  1. Open app.py.
  2. Set level=logging.INFO in basicConfig.
  3. Restart the app and send a request again.

When it is red 2

ModuleNotFoundError: No module named 'flask'

Cause. Flask is not installed in the active Python.

Fix, step by step

  1. Activate the env: . .venv/bin/activate
  2. pip install flask
  3. Run python app.py again.

When it is red 3

OSError: [Errno 98] Address already in use

Cause. Another program already uses port 5000.

Fix, step by step

  1. Find it: sudo ss -ltnp | grep 5000
  2. Stop it, or change app.run(port=5001).
  3. Retry the curl on the new port.

Cleanup

  1. Stop the apps

    pkill -f app.py ; pkill -f server.js
    

    What it does: Stops the lab apps.

    Output

    (no output)
    
  2. Remove nginx if you do not need it

    sudo apt-get remove -y nginx
    

    What it does: Frees port 80.

    Output

    Removing nginx ...
    

Ravindra Bagale's Tip

A log is the server diary. Write a good diary and at 2 am you find the problem in 2 minutes.

Practice tasks

Easy Add the order amount

Why: More fields make searching easy.

What to do: Log amount=... in every payment line.

How:
  1. Read amount from the query string.
  2. Add it to log.info.

Check: Every line shows order and amount.

Medium Write logs to a file too

Why: Some old servers still need log files.

What to do: Add a FileHandler that writes pay.log.

How:
  1. logging.basicConfig(handlers=[logging.StreamHandler(), logging.FileHandler("pay.log")])

Check: Lines appear on screen and in pay.log.

Hard Match three logs for one request

Why: Real bugs cross nginx, app and database.

What to do: Put nginx in front of the Flask app and find one request in both logs by time.

How:
  1. proxy_pass http://127.0.0.1:5000;
  2. Send one request.
  3. grep the same second in both files.

Check: You see the same request in the nginx log and the app log.

Easy Say logs 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 logs 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, add a third route /refund to app.py that logs INFO on success and WARNING when amount is more than 5000. Find the WARNING line with grep.

Recap

  • Logs are the flight recorder of a server.
  • Every line needs time, level and a clear message.
  • Use ERROR for failures and add the stack trace.
  • Python, Node.js and nginx all write logs in a similar shape.
  • Good logs turn a two hour guess into a two minute search.

FAQ

Should I log everything at DEBUG in production?

No. It is slow and costly. Use INFO in production and turn on DEBUG only for a short time.

Is print() the same as logging?

print works, but logging adds time, level and easy control. Use logging.

Which time zone should logs use?

UTC is best for servers. Show the zone if you use local time.

Do I need a tool like ELK to start?

No. Start with good lines and grep. Tools come later.

What is the difference between a log and a metric?

A log is one event with detail. A metric is a number over time, like errors per minute.

Interview questions

  1. Why are logs important in DevOps?

    They tell us what happened and when, so we can find the root cause of an incident fast.

  2. What should a good log line contain?

    Time, level, service name, a clear message and ids like order id or request id.

  3. What are log levels?

    DEBUG, INFO, WARNING, ERROR, CRITICAL. They say how serious a line is and let us filter.

  4. Where do nginx logs live?

    By default /var/log/nginx/access.log and error.log.

  5. Tell me about a time logs helped you.

    Example: a 500 error at Swiggy-like checkout; the log showed "db timeout after 3000ms" and we raised the pool size.

Quick quiz

Q1. What is a log?

A line a program writes to say what it did, with time.

Q2. Which level is for a failure?

ERROR.

Q3. What does log.exception add?

The full stack trace.

Q4. Where does nginx write 404 lines?

/var/log/nginx/access.log.

Q5. Why is a timestamp important?

It lets you match the log line with the time the user saw the problem.

Did you understand? Let us try it once more.

Ravi Sir's Cards for this lesson

मराठी cards