TExcelTAD
Home › Automation Scripting: Bash, Python & Go › Logging for Scripts

Logging for Scripts

print() is fine while you write a script. Once it runs from cron, CI or a container, you want levels you can turn up and down, messages on stderr, a consistent format, and sometimes machine-readable JSON lines for a log collector. The standard logging module provides all of that. This lesson shows the setup that fits automation scripts, and the few mistakes that make logs useless.

The minimum setup

One basicConfig call in main, one logger per module, and log calls with arguments rather than f-strings:

python · try it yourself
import logging
import sys

log = logging.getLogger("backup")          # usually logging.getLogger(__name__)

def backup(dbs):
    log.info("starting backup of %d database(s)", len(dbs))
    for db in dbs:
        log.debug("dumping %s", db)
        if db == "legacy":
            log.warning("skipping %s: marked read-only", db)
            continue
    log.info("backup finished")

# In a real script: stream=sys.stderr (the default). stdout is used here so the order is easy to read.
logging.basicConfig(level=logging.INFO, stream=sys.stdout,
                    format="%(levelname)-7s %(name)s: %(message)s", force=True)
backup(["shop", "legacy", "auth"])

print("--- with DEBUG enabled")
logging.getLogger().setLevel(logging.DEBUG)
backup(["shop"])
INFO    backup: starting backup of 3 database(s)
WARNING backup: skipping legacy: marked read-only
INFO    backup: backup finished
--- with DEBUG enabled
INFO    backup: starting backup of 1 database(s)
DEBUG   backup: dumping shop
INFO    backup: backup finished
  • Levels: DEBUG for details you only want while investigating, INFO for what the script did, WARNING for something unexpected that it handled, ERROR for a failure, CRITICAL for "giving up". Pick the level from an option or an environment variable (--verbose, LOG_LEVEL), not by editing the code.
  • log.info("… %s", value), not f-strings: the message is only formatted if the level is enabled, and log aggregators can group messages by their template.
  • Libraries never call basicConfig; only the program's entry point does. That is why it sits in main.

Exceptions with tracebacks

log.exception() logs at ERROR level and appends the traceback of the exception being handled, which is exactly what you want in a except block at the top of a script:

python · try it yourself
import logging
import sys

logging.basicConfig(level=logging.INFO, stream=sys.stdout, format="%(levelname)s %(message)s", force=True)
log = logging.getLogger("rotate")

def parse_retention(value):
    return int(value)

def main():
    try:
        days = parse_retention("7d")
    except ValueError:
        log.exception("invalid retention setting")
        return 2
    log.info("keeping %d days", days)
    return 0

print("exit", main())
ERROR invalid retention setting
Traceback (most recent call last):
  File "<exec>", line 12, in main
  File "<exec>", line 8, in parse_retention
ValueError: invalid literal for int() with base 10: '7d'
exit 2

force=True replaces any logging setup made earlier (useful in notebooks and in this playground, where the interpreter is reused between runs).

Timestamps and where logs go

Where the script runs Format
interactively level and message are enough
cron, plain files add a UTC timestamp: %(asctime)s with converter = time.gmtime
systemd service, container the journal / container runtime adds the time; keep level and message
shipped to Loki, Elasticsearch, CloudWatch one JSON object per line
python
import logging, time

handler = logging.StreamHandler()                    # stderr
fmt = logging.Formatter("%(asctime)s %(levelname)s %(name)s: %(message)s", "%Y-%m-%dT%H:%M:%SZ")
fmt.converter = time.gmtime                          # UTC, matching the trailing Z
handler.setFormatter(fmt)
logging.basicConfig(level=logging.INFO, handlers=[handler])
# 2026-01-15T10:00:00Z INFO backup: starting backup of 3 database(s)

JSON lines with context

A JSON formatter is a few lines. extra= attaches fields to one record; a LoggerAdapter attaches the same fields (a run ID, the environment) to every record. The example sets a fixed time on each record so the output is repeatable; a real formatter uses record.created:

python · try it yourself
import json
import logging
import sys
from datetime import datetime, timezone

class JsonFormatter(logging.Formatter):
    FIELDS = ("run_id", "env", "service", "duration_ms")
    def format(self, record):
        entry = {
            "ts": datetime.fromtimestamp(record.created, timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z"),
            "level": record.levelname.lower(),
            "logger": record.name,
            "msg": record.getMessage(),
        }
        entry.update({k: getattr(record, k) for k in self.FIELDS if hasattr(record, k)})
        if record.exc_info:
            entry["error"] = self.formatException(record.exc_info).splitlines()[-1]
        return json.dumps(entry)

class FixedClock(logging.Filter):                    # demo only: a fixed timestamp for repeatable output
    def filter(self, record):
        record.created = 1768471200.0                # 2026-01-15T10:00:00Z
        return True

handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(JsonFormatter())
handler.addFilter(FixedClock())
logging.basicConfig(level=logging.INFO, handlers=[handler], force=True)

log = logging.LoggerAdapter(logging.getLogger("deploy"), {"run_id": "r-1042", "env": "prod"},
                            merge_extra=True)    # Python 3.13+
log.info("deploy started")
log.info("service updated", extra={"service": "shop-api", "duration_ms": 1840})
try:
    {}["replicas"]
except KeyError:
    log.exception("deploy failed")
{"ts": "2026-01-15T10:00:00Z", "level": "info", "logger": "deploy", "msg": "deploy started", "run_id": "r-1042", "env": "prod"}
{"ts": "2026-01-15T10:00:00Z", "level": "info", "logger": "deploy", "msg": "service updated", "run_id": "r-1042", "env": "prod", "service": "shop-api", "duration_ms": 1840}
{"ts": "2026-01-15T10:00:00Z", "level": "error", "logger": "deploy", "msg": "deploy failed", "run_id": "r-1042", "env": "prod", "error": "KeyError: 'replicas'"}

Each line is one complete JSON document, so jq (and every log pipeline) can filter it: … 2>&1 | jq -c 'select(.level == "error")'. merge_extra=True (new in Python 3.13) merges each call's extra with the adapter's fields. Without it, and on older versions, the adapter's dictionary replaces per-call extra, and service and duration_ms would silently disappear from the second line.

Mistakes that make logs useless

  • Logging secrets. Tokens in URLs, Authorization headers, full request bodies. Log the endpoint and the status, not the credentials; redact before logging.
  • Logging to stdout in a script whose stdout is data (tool | jq): the next tool chokes on log lines.
  • Logging and re-raising at every level. One failure produces five tracebacks. Log once, where you handle it.
  • No context. "Request failed" is useless at 3 a.m.; "GET /v1/services/shop-api -> HTTP 503 after 5 attempts" is a diagnosis.

Test yourself

Why write log.info("copied %d files", n) instead of log.info(f"copied {n} files")?

  1. f-strings are not allowed in logging
  2. The message is only formatted when the level is enabled, and aggregators can group by the template
  3. It is required for JSON output
  4. It is faster to type

What does log.exception("msg") add compared to log.error("msg")?

  1. Nothing
  2. The traceback of the exception currently being handled
  3. It exits the program
  4. It sends an email

Where should a script that runs as a systemd service send its log lines?

  1. A file in /tmp
  2. stderr (or stdout), which the journal collects and timestamps
  3. A database
  4. Nowhere