Skip to content

Structured logging in Python with Loguru and stdlib alternatives

Emit structured JSON logs from a Python service with Loguru, plus the stdlib python-json-logger path — including journald, log rotation, and Sentry forwarding.

Structured logging — emitting key-value pairs rather than free-form lines — is the difference between grep-able logs and queryable logs. Loguru wraps the awkward stdlib logging module with one-line setup, automatic exception formatting, and JSON output. structlog and python-json-logger are the alternatives if you’re committed to the stdlib path. This article wires Loguru for production with journald rotation, level filters, and downstream forwarding to Sentry or Loki.

How to verify

Confirm the logger is emitting and the format is what you expect:

pip show loguru python-json-logger structlog | grep -E "^Name|^Version"
journalctl -u my-app -n 30 --output=json --no-pager | head -3 | jq .
journalctl -u my-app -n 10 --output=cat
python -c "from loguru import logger; logger.bind(req_id='abc').info('hello', user=42)"
ls /var/log/app/ 2>/dev/null

If your journal output is free-text and not JSON, the app is writing to stderr without JSON serialisation — see step 2.

What’s happening

The stdlib logging module has good bones — handlers, formatters, level filters — but the API is verbose. The simplest “I want JSON to stdout” takes 15 lines of config. Loguru replaces that with one import and one method:

from loguru import logger
logger.add("stderr", serialize=True)
logger.info("request handled", path="/api/orders", status=200)

The serialize=True flag emits one JSON object per line with the message, level, timestamp, source location, and any keyword args you passed. journald or Promtail or Datadog Agent picks it up from stderr and ships to your log system. structlog has a similar philosophy with more flexibility and less magic; python-json-logger is the most minimal — it’s just a Formatter for stdlib logging that writes JSON.

The other thing structured logging buys you is context binding. A web request gets a request ID at ingress; every log line for the duration of that request includes the ID without the route code having to thread it through. Loguru does this with logger.bind(); structlog does it with structlog.contextvars.

The procedure

  1. Install Loguru. For Sentry forwarding, add loguru-sentry or use Sentry’s stdlib integration:

    /opt/venvs/app/bin/pip install loguru
  2. Replace stdlib logging config with a Loguru bootstrap. In app/log_setup.py:

    import os
    import sys
    from loguru import logger
    
    def setup():
        logger.remove()                     # drop default sink
        logger.add(
            sys.stderr,
            level=os.environ.get("LOG_LEVEL", "INFO"),
            serialize=True,                 # JSON output
            backtrace=False,                # don't dump frames on logger.exception unless needed
            diagnose=False,                 # don't include local vars (PII risk)
            enqueue=True,                   # thread-safe + async-safe
        )

    Call setup() once at app start. enqueue=True is the production-safe knob — it pushes the formatting and IO to a background thread so the calling code isn’t blocked.

  3. Bind a request ID at ingress. In FastAPI:

    from fastapi import Request
    from loguru import logger
    import uuid
    
    @app.middleware("http")
    async def log_request(request: Request, call_next):
        req_id = request.headers.get("X-Request-ID") or str(uuid.uuid4())
        with logger.contextualize(req_id=req_id, path=request.url.path):
            response = await call_next(request)
            logger.info("request", method=request.method, status=response.status_code)
        return response

    Every logger.info(...) inside that block automatically includes req_id and path.

  4. Bridge stdlib logging to Loguru so libraries (Django, SQLAlchemy, urllib3) get the same treatment:

    import logging
    from loguru import logger
    
    class InterceptHandler(logging.Handler):
        def emit(self, record):
            level = logger.level(record.levelname).name if logger.level(record.levelname) else record.levelno
            frame, depth = logging.currentframe(), 2
            while frame.f_code.co_filename == logging.__file__:
                frame = frame.f_back
                depth += 1
            logger.opt(depth=depth, exception=record.exc_info).log(level, record.getMessage())
    
    logging.basicConfig(handlers=[InterceptHandler()], level=0, force=True)

    Now django.request.warning(...) goes through Loguru’s JSON formatter.

  5. Forward to Sentry. Sentry’s stdlib integration captures logger.error and logger.exception automatically:

    import sentry_sdk
    sentry_sdk.init(
        dsn=os.environ["SENTRY_DSN"],
        integrations=[
            sentry_sdk.integrations.logging.LoggingIntegration(
                level=logging.INFO,         # capture INFO as breadcrumbs
                event_level=logging.ERROR,  # send ERROR as events
            ),
        ],
    )

    Because step 4 bridges Loguru into stdlib, the Sentry integration sees Loguru’s records.

  6. systemd captures stderr to journald by default. To verify the JSON is preserved, query with --output=json:

    journalctl -u my-app --output=json -n 5 | jq '.MESSAGE | fromjson | {level, message, req_id}'
  7. For file logging with rotation (when journald isn’t enough — e.g., volume mounted in Docker), add a rotating file sink:

    logger.add(
        "/var/log/app/app.json",
        rotation="100 MB",
        retention="14 days",
        compression="gz",
        serialize=True,
    )

    Loguru handles rotation in-process; no logrotate cron needed.

Common pitfalls

  • diagnose=True in production — Loguru’s diagnose mode dumps local variables on every exception, which includes PII (request body, user objects). Always diagnose=False in prod.
  • Writing to a file path that the systemd unit can’t write to — User=deploy plus /var/log/app/ owned by root yields silent failure. Use RuntimeDirectory=app and write under /run/app/, or chown deploy:adm /var/log/app/.
  • Mixing print() and logger.info() — print() goes to stdout unformatted, breaking the structured pipeline. Find them with grep -r 'print(' app/ | grep -v test.
  • Forgetting enqueue=True in an async app — without it, a slow log sink (network) blocks the event loop. With it, formatting happens off the loop.
  • Logging the full request body — even at DEBUG level, this captures passwords on login endpoints. Whitelist the fields you log, never blacklist.

For the Sentry side of the same observability stack, see Debugging Django in production without DEBUG=True. Stack Harbor’s managed operations practice ships Loguru-formatted JSON to journald on every Python client, and forwards to Loki via Promtail or to Datadog via the Agent — the same upstream shape regardless of where logs land.