Skip to content

splatlog.json.json_formatter

JSONFormatter

class JSONFormatter(logging.Formatter)

[view_source]

Howdy

format

def format(record: logging.LogRecord) -> str

[view_source]

Examples

Basic example.

>>> from splatlog._testing import make_log_record

>>> r_1 = make_log_record(
...     created=datetime(
...         2022, 9, 4, 3, 4, 5, 123456, tzinfo=timezone.utc
...     )
... )

>>> formatter = JSONFormatter(
...     encoder=JSONEncoder.pretty(),
...     tz=timezone.utc,
... )

>>> print(formatter.format(r_1))
{
    "t": "2022-09-04T03:04:05.123456Z",
    "level": "INFO",
    "name": "splatlog._testing",
    "file": ".../splatlog/_testing.py",
    "line": 123,
    "msg": "Test message"
}

With some data attached.

>>> from splatlog._testing import make_log_record

>>> r_2 = make_log_record(
...     created=datetime(
...         2022, 9, 4, 3, 4, 5, 123456, tzinfo=timezone.utc
...     ),
...     data=dict(
...         x=1,
...         y=2,
...     )
... )

>>> print(formatter.format(r_2))
{
    "t": "2022-09-04T03:04:05.123456Z",
    "level": "INFO",
    "name": "splatlog._testing",
    "file": ".../splatlog/_testing.py",
    "line": 123,
    "msg": "Test message",
    "data": {
        "x": 1,
        "y": 2
    }
}

With error information (exc_info).

>>> import sys
>>> from splatlog._testing import make_log_record

>>> try:
...     raise RuntimeError("Something went wrong")
... except:
...     r_3 = make_log_record(
...         created=datetime(
...             2022, 9, 4, 3, 4, 5, 123456, tzinfo=timezone.utc
...         ),
...         exc_info=sys.exc_info(),
...     )
...     print(formatter.format(r_3))
{
    "t": "2022-09-04T03:04:05.123456Z",
    "level": "INFO",
    "name": "splatlog._testing",
    "file": ".../splatlog/_testing.py",
    "line": 123,
    "msg": "Test message",
    "error": {
        "type": "RuntimeError",
        "msg": "Something went wrong",
        "traceback": [
            {
                "file": "<doctest ...>",
                "line": 2,
                "name": "<module>",
                "text": "raise RuntimeError(\\"Something went wrong\\")"
            }
        ]
    }
}