Skip to main content

JSON formatter for python logging

Project description

JSON formatter for logging

pypi version Build status Coverage Code style: black Number of tests Number of downloads

This module provides a JSON formatter for the python logging module that will format to JSON formatted string.

Using this formatter allows to have the proper format for logging to Splunk or ElasticSearch, but it can also be used for logging to stdout as a string is issued.

Features

Adding additional fields and values

You can add fields to every message that is being logged. To do so, specify the fields parameter to the logging_json.JSONFormatter instance.

It must be a dictionary where keys are the keys to be appended to the resulting JSON dictionary (if not already present) and the values can be one of the following:

  • An attribute of the logging record (non-exhaustive list can be found on the python logging documentation).
  • If not found on the record, the value will be linked to the key.

Logging exceptions, a specific case

If an exception is logged, the exception key will be appended to the resulting JSON dictionary.

This dictionary will contains 3 keys:

  • type: The name of the exception class (useful when the message is blank).
  • message: The str representation of the exception (usually the provided error message).
  • stack: The stack trace, formatted as a string.

Logging with a dictionary

This formatter allows you to log dictionary as in the following:

import logging

logging.info({"key": "value", "other key": "other value"})

The resulting JSON dictionary will be the one you provided (with the additional fields).

Logging with anything else (such as a string)

Anything not logged using a dictionary will be handled by the standard formatter and it can result in one of the 2 output:

  • A JSON dictionary, if additional fields are set or if extra parameter is used while logging, with the message available in the msg key of the resulting JSON dictionary. Default msg key name can be changed by message_field_name parameter of the logging_json.JSONFormatter instance.
  • The formatted record, if no additional fields are set.

This handles the usual string logging as in the following:

import logging

logging.info("This is my message")

Configuration

You can create a formatter instance yourself as in the following or you can use a logging configuration.

import logging_json

formatter = logging_json.JSONFormatter(fields={
    "level_name": "levelname",
    "thread_name": "threadName",
    "process_name": "processName"
})

Using logging.config.dictConfig

You can configure your logging as advertise by python, by using the logging.config.dictConfig function.

dict configuration

import logging.config

logging.config.dictConfig({
    "version": 1,
    "formatters": {
        "json": {
            '()': 'logging_json.JSONFormatter',
            'fields':{
                "level_name": "levelname",
                "thread_name": "threadName",
                "process_name": "processName"
            }
        }
    },
    "handlers": {
        "standard_output": {
            'class': 'logging.StreamHandler',
            'formatter': 'json',
            'stream': 'ext://sys.stdout'
        },
    },
    "loggers": {
        "my_app": {"level": "DEBUG"}
    },
    "root": {
        "level": "INFO",
        "handlers": ["standard_output"]
    }
})

YAML logging configuration

You can use YAML to store your logging configuration, as in the following sample:

import logging.config
import yaml

with open("path/to/logging_configuration.yaml", "r") as config_file:
    logging.config.dictConfig(yaml.load(config_file))

Where logging_configuration.yaml can be a file containing the following sample:

version: 1
formatters:
  json:
    '()': logging_json.JSONFormatter
    fields:
      level_name: levelname
      thread_name: threadName
      process_name: processName
handlers:
  standard_output:
    class: logging.StreamHandler
    formatter: json
    stream: ext://sys.stdout
loggers:
  my_app:
    level: DEBUG
root:
  level: INFO
  handlers: [standard_output]

How to install

  1. python 3.6+ must be installed
  2. Use pip to install module:
python -m pip install logging_json

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

logging_json-0.2.0.tar.gz (5.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

logging_json-0.2.0-py3-none-any.whl (5.9 kB view details)

Uploaded Python 3

File details

Details for the file logging_json-0.2.0.tar.gz.

File metadata

  • Download URL: logging_json-0.2.0.tar.gz
  • Upload date:
  • Size: 5.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.6.0 importlib_metadata/4.8.2 pkginfo/1.8.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.7.12

File hashes

Hashes for logging_json-0.2.0.tar.gz
Algorithm Hash digest
SHA256 cfa17c4bf09f5ac70f7970aaeeff8c84b0dc2ed5ddd9d1442184a532911f04f2
MD5 3567802efec87d52e26f6992ca33735f
BLAKE2b-256 bebe11e988108c0f31c755e506ce2307a6b291a267eaf18f6dbe1c07c208e378

See more details on using hashes here.

File details

Details for the file logging_json-0.2.0-py3-none-any.whl.

File metadata

  • Download URL: logging_json-0.2.0-py3-none-any.whl
  • Upload date:
  • Size: 5.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.6.0 importlib_metadata/4.8.2 pkginfo/1.8.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.7.12

File hashes

Hashes for logging_json-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 b0c382af89a83d2b1a2ba40345a8636ddd43f43f714ef2396f98c91c188fedf7
MD5 fc7dbde1a11e04de4a90bd28b7c61bca
BLAKE2b-256 d098caaebae39dfaef82f21b462cc86394c20ee0bf99b5fc9c9be44f7426d7ac

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page