Monitoring python Intermediate

Structured JSON Log Formatter

Python logging handler that outputs structured JSON logs compatible with any log aggregator.

python
import logging, json, traceback

class JSONFormatter(logging.Formatter):
    def format(self, record: logging.LogRecord) -> str:
        log = {
            'level':   record.levelname,
            'message': record.getMessage(),
            'logger':  record.name,
            'ts':      self.formatTime(record),
        }
        if record.exc_info:
            log['exception'] = traceback.format_exception(*record.exc_info)
        return json.dumps(log)

handler = logging.StreamHandler()
handler.setFormatter(JSONFormatter())
logging.getLogger().addHandler(handler)

Prerequisites

  • python >= 3.9

Pro Tips

  • → Ship JSON logs to Loki or Elasticsearch with Promtail/Filebeat.

Was this module useful?

Share your experience — it helps the team improve.

Leave Feedback

Commercial Licensing

Acquire a production access token or template license for enterprise deployment.

Module Info

Language
python
Level
Intermediate
Read time
3 min
Published
Apr 2025
License
Commercial License

Newsletter

New modules every week, directly to your inbox.