How to add a timestamp and loglevel to each log in Python's structlog?

937 Views Asked by At

How to configure structlog so it automatically adds loglevel and a timestamp (and maybe other fields) by default to each log message it logs? So I do not have to add it to every message explicitly.

I am displaying my messages as JSON (for further processing with Fluentd, Elasticsearch and Kibana). loglevel is not (for some reason) included in the output JSON log.

That is how I confiure my structlog.

structlog.configure(
        processors=[structlog.processors.JSONRenderer()],
        wrapper_class=structlog.make_filtering_bound_logger(logging.INFO),
    )

I am logging:

log.info("Artist saved", spotify_id=id)

Logs I am seeing (mind no time and no loglevel):

{"logger": "get_artists.py", "spotify_id": "4Y6z2aIww27vnxZz9xfG3S",  "event": "Artist saved"}
1

There are 1 best solutions below

0
On

I found my answer here: Python add extra fields to structlog-based formatters within logging

There are processors that are doing exactly what I needed:

structlog.configure(
        processors=[
            structlog.processors.add_log_level,
            structlog.processors.TimeStamper(fmt="iso", key="ts"),
            structlog.processors.JSONRenderer(),
        ],
        wrapper_class=structlog.make_filtering_bound_logger(logging.INFO),
    )

Adding both, add_log_level and TimeStamper resulted, as expected in the extra fields in the log ..., "level": "info", "ts": "2022-04-17T19:21:56.426093Z"}.