• Stars
    star
    103
  • Rank 333,046 (Top 7 %)
  • Language
    Python
  • License
    MIT License
  • Created about 9 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Python JSON log formatter

JSON log formatter 🪵

The library helps you to store logs in JSON format. Why is it important? Well, it facilitates integration with Logstash.

Usage example:

import logging

import json_log_formatter

formatter = json_log_formatter.JSONFormatter()

json_handler = logging.FileHandler(filename='/var/log/my-log.json')
json_handler.setFormatter(formatter)

logger = logging.getLogger('my_json')
logger.addHandler(json_handler)
logger.setLevel(logging.INFO)

logger.info('Sign up', extra={'referral_code': '52d6ce'})

try:
    raise ValueError('something wrong')
except ValueError:
    logger.error('Request failed', exc_info=True)

The log file will contain the following log record (inline).

{
    "message": "Sign up",
    "time": "2015-09-01T06:06:26.524448",
    "referral_code": "52d6ce"
}
{
    "message": "Request failed",
    "time": "2015-09-01T06:06:26.524449",
    "exc_info": "Traceback (most recent call last): ..."
}

If you use a log collection and analysis system, you might need to include the built-in log record attributes with VerboseJSONFormatter.

json_handler.setFormatter(json_log_formatter.VerboseJSONFormatter())
logger.error('An error has occured')
{
    "filename": "tests.py",
    "funcName": "test_file_name_is_testspy",
    "levelname": "ERROR",
    "lineno": 276,
    "module": "tests",
    "name": "my_json",
    "pathname": "/Users/bob/json-log-formatter/tests.py",
    "process": 3081,
    "processName": "MainProcess",
    "stack_info": null,
    "thread": 4664270272,
    "threadName": "MainThread",
    "message": "An error has occured",
    "time": "2021-07-04T21:05:42.767726"
}

JSON libraries

You can use ujson or simplejson instead of built-in json library.

import json_log_formatter
import ujson

formatter = json_log_formatter.JSONFormatter()
formatter.json_lib = ujson

Note, ujson doesn't support dumps(default=f) argument: if it can't serialize an attribute, it might fail with TypeError or skip an attribute.

Django integration

Here is an example of how the JSON formatter can be used with Django.

LOGGING['formatters']['json'] = {
    '()': 'json_log_formatter.JSONFormatter',
}
LOGGING['handlers']['json_file'] = {
    'level': 'INFO',
    'class': 'logging.FileHandler',
    'filename': '/var/log/my-log.json',
    'formatter': 'json',
}
LOGGING['loggers']['my_json'] = {
    'handlers': ['json_file'],
    'level': 'INFO',
}

Let's try to log something.

import logging

logger = logging.getLogger('my_json')

logger.info('Sign up', extra={'referral_code': '52d6ce'})

Custom formatter

You will likely need a custom log formatter. For instance, you want to log a user ID, an IP address and time as django.utils.timezone.now(). To do so you should override JSONFormatter.json_record().

class CustomisedJSONFormatter(json_log_formatter.JSONFormatter):
    def json_record(self, message: str, extra: dict, record: logging.LogRecord) -> dict:
        extra['message'] = message
        extra['user_id'] = current_user_id()
        extra['ip'] = current_ip()

        # Include builtins
        extra['level'] = record.levelname
        extra['name'] = record.name

        if 'time' not in extra:
            extra['time'] = django.utils.timezone.now()

        if record.exc_info:
            extra['exc_info'] = self.formatException(record.exc_info)

        return extra

Let's say you want datetime to be serialized as timestamp. You can use ujson (which does it by default) and disable ISO8601 date mutation.

class CustomisedJSONFormatter(json_log_formatter.JSONFormatter):
    json_lib = ujson

    def mutate_json_record(self, json_record):
        return json_record

Tests

$ pip install -r requirements.txt
$ tox

More Repositories

1

flask-api-utils

Flask extension that takes care of API representation and authentication.
Python
55
star
2

gopher-celery

A tool to place/process Celery tasks in Go.
Go
40
star
3

distributed-payment

Demo execution of a payment transaction without an atomic commit across 3 partitions.
Go
34
star
4

capacity

Capacity management demo based on Jon Moore's talk https://www.youtube.com/watch?v=m64SWl9bfvk.
Go
33
star
5

ddd-err

Error handling example in DDD project with Go kit.
Go
15
star
6

libbpf-tools

Go frontend for libbpf-tools.
C
13
star
7

prometheus-on-kubernetes

Web app monitoring with Prometheus toolkit running on Kubernetes
Go
11
star
8

diy-parca-agent

CPU profiler based on https://github.com/parca-dev/parca-agent.
C
8
star
9

api-example-based-on-flask

API example based on Flask
Python
8
star
10

lsb

BMP steganography
Python
7
star
11

alg

Go implementation of some examples from Algorithms book.
Go
7
star
12

abstract-internal-messaging-deploy

Deploy Abstract Internal Messaging System
Scheme
6
star
13

systemd

Client to access systemd services via D-Bus.
Go
6
star
14

distributed-signup

Partitioned signup demo based on Kafka.
Go
5
star
15

pyodnoklassniki

Odnoklassniki REST API wrapper.
Python
4
star
16

apigate

API gateway examples (Traefik, Ambassador, Envoy).
Go
4
star
17

bloom

Bloom filter (space-efficient probabilistic data structure).
Go
3
star
18

bitgo-v2

Go client for BitGo.com API v2
Go
3
star
19

bitgo-v1

Go client for BitGo.com API v1
Go
2
star
20

salt-stack-example

Fat-free example of SaltStack configuration.
Scheme
2
star
21

django-prometheus-via-statsd

Instrumenting Django with Prometheus and StatsD.
Python
1
star
22

pg-time

Testing Go time.Time and PostgreSQL Timestamptz
Go
1
star
23

django-todo

Простое управление цепочками задач
Python
1
star
24

awscreds

Improving AWS Go SDK latency on EKS https://github.com/aws/aws-sdk-go/issues/4385.
Go
1
star
25

interview

Interview notes.
Go
1
star
26

abstract-internal-messaging

This is an interview test task.
Python
1
star
27

pg-keepalive

Available options to control TCP keepalive in lib/pq.
Go
1
star
28

upload-a-file

It's the Flask app that shows examples of file uploading
Python
1
star
29

blockchain-info

Go client for the Blockchain.info API
Go
1
star
30

slack-bender

Slack bot which uses web socket API to print messages
Go
1
star
31

kafka-for-gophers

Slides about writing reliable Go programs that use Kafka.
1
star
32

marselester.github.com

Blog
HTML
1
star
33

api-proxy-example

Example of API proxy.
Python
1
star