python-json-logger


Namepython-json-logger JSON
Version 2.0.7 PyPI version JSON
download
home_pagehttp://github.com/madzak/python-json-logger
SummaryA python library adding a json log formatter
upload_time2023-02-21 17:40:06
maintainer
docs_urlNone
authorZakaria Zajac
requires_python>=3.6
licenseBSD
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            ![Build Status](https://github.com/madzak/python-json-logger/actions/workflows/build.yml/badge.svg)
[![License](https://img.shields.io/pypi/l/python-json-logger.svg)](https://pypi.python.org/pypi/python-json-logger/)
[![Version](https://img.shields.io/pypi/v/python-json-logger.svg)](https://pypi.python.org/pypi/python-json-logger/)

Overview
=======
This library is provided to allow standard python logging to output log data as json objects. With JSON we can make our logs more readable by machines and we can stop writing custom parsers for syslog type records.

News
=======
Hi, I see this package is quiet alive and I am sorry for ignoring it so long. I will be stepping up my maintenance of this package so please allow me a week to get things back in order (and most likely a new minor version) and I'll post and update here once I am caught up.

Installing
==========
Pip:

    pip install python-json-logger

Pypi:

   https://pypi.python.org/pypi/python-json-logger

Manual:

    python setup.py install

Usage
=====

## Integrating with Python's logging framework

Json outputs are provided by the JsonFormatter logging formatter. You can add the custom formatter like below:

**Please note: version 0.1.0 has changed the import structure, please update to the following example for proper importing**

```python
    import logging
    from pythonjsonlogger import jsonlogger

    logger = logging.getLogger()

    logHandler = logging.StreamHandler()
    formatter = jsonlogger.JsonFormatter()
    logHandler.setFormatter(formatter)
    logger.addHandler(logHandler)
```

## Customizing fields

The fmt parser can also be overidden if you want to have required fields that differ from the default of just `message`.

These two invocations are equivalent:

```python
class CustomJsonFormatter(jsonlogger.JsonFormatter):
    def parse(self):
        return self._fmt.split(';')

formatter = CustomJsonFormatter('one;two')

# is equivalent to:

formatter = jsonlogger.JsonFormatter('%(one)s %(two)s')
```

You can also add extra fields to your json output by specifying a dict in place of message, as well as by specifying an `extra={}` argument.

Contents of these dictionaries will be added at the root level of the entry and may override basic fields.

You can also use the `add_fields` method to add to or generally normalize the set of default set of fields, it is called for every log event. For example, to unify default fields with those provided by [structlog](http://www.structlog.org/) you could do something like this:

```python
class CustomJsonFormatter(jsonlogger.JsonFormatter):
    def add_fields(self, log_record, record, message_dict):
        super(CustomJsonFormatter, self).add_fields(log_record, record, message_dict)
        if not log_record.get('timestamp'):
            # this doesn't use record.created, so it is slightly off
            now = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%fZ')
            log_record['timestamp'] = now
        if log_record.get('level'):
            log_record['level'] = log_record['level'].upper()
        else:
            log_record['level'] = record.levelname

formatter = CustomJsonFormatter('%(timestamp)s %(level)s %(name)s %(message)s')
```

Items added to the log record will be included in *every* log message, no matter what the format requires.

## Adding custom object serialization

For custom handling of object serialization you can specify default json object translator or provide a custom encoder

```python
def json_translate(obj):
    if isinstance(obj, MyClass):
        return {"special": obj.special}

formatter = jsonlogger.JsonFormatter(json_default=json_translate,
                                     json_encoder=json.JSONEncoder)
logHandler.setFormatter(formatter)

logger.info({"special": "value", "run": 12})
logger.info("classic message", extra={"special": "value", "run": 12})
```

## Using a Config File

To use the module with a config file using the [`fileConfig` function](https://docs.python.org/3/library/logging.config.html#logging.config.fileConfig), use the class `pythonjsonlogger.jsonlogger.JsonFormatter`. Here is a sample config file.

```ini
[loggers]
keys = root,custom

[logger_root]
handlers =

[logger_custom]
level = INFO
handlers = custom
qualname = custom

[handlers]
keys = custom

[handler_custom]
class = StreamHandler
level = INFO
formatter = json
args = (sys.stdout,)

[formatters]
keys = json

[formatter_json]
format = %(message)s
class = pythonjsonlogger.jsonlogger.JsonFormatter
```

Example Output
==============

Sample JSON with a full formatter (basically the log message from the unit test). Every log message will appear on 1 line like a typical logger.

```json
{
    "threadName": "MainThread",
    "name": "root",
    "thread": 140735202359648,
    "created": 1336281068.506248,
    "process": 41937,
    "processName": "MainProcess",
    "relativeCreated": 9.100914001464844,
    "module": "tests",
    "funcName": "testFormatKeys",
    "levelno": 20,
    "msecs": 506.24799728393555,
    "pathname": "tests/tests.py",
    "lineno": 60,
    "asctime": ["12-05-05 22:11:08,506248"],
    "message": "testing logging format",
    "filename": "tests.py",
    "levelname": "INFO",
    "special": "value",
    "run": 12
}
```

External Examples
=================

- [Wesley Tanaka - Structured log files in Python using python-json-logger](http://web.archive.org/web/20201130054012/https://wtanaka.com/node/8201)

- [Archive](https://web.archive.org/web/20201130054012/https://wtanaka.com/node/8201)

            

Raw data

            {
    "_id": null,
    "home_page": "http://github.com/madzak/python-json-logger",
    "name": "python-json-logger",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.6",
    "maintainer_email": "",
    "keywords": "",
    "author": "Zakaria Zajac",
    "author_email": "zak@madzak.com",
    "download_url": "https://files.pythonhosted.org/packages/4f/da/95963cebfc578dabd323d7263958dfb68898617912bb09327dd30e9c8d13/python-json-logger-2.0.7.tar.gz",
    "platform": null,
    "description": "![Build Status](https://github.com/madzak/python-json-logger/actions/workflows/build.yml/badge.svg)\n[![License](https://img.shields.io/pypi/l/python-json-logger.svg)](https://pypi.python.org/pypi/python-json-logger/)\n[![Version](https://img.shields.io/pypi/v/python-json-logger.svg)](https://pypi.python.org/pypi/python-json-logger/)\n\nOverview\n=======\nThis library is provided to allow standard python logging to output log data as json objects. With JSON we can make our logs more readable by machines and we can stop writing custom parsers for syslog type records.\n\nNews\n=======\nHi, I see this package is quiet alive and I am sorry for ignoring it so long. I will be stepping up my maintenance of this package so please allow me a week to get things back in order (and most likely a new minor version) and I'll post and update here once I am caught up.\n\nInstalling\n==========\nPip:\n\n    pip install python-json-logger\n\nPypi:\n\n   https://pypi.python.org/pypi/python-json-logger\n\nManual:\n\n    python setup.py install\n\nUsage\n=====\n\n## Integrating with Python's logging framework\n\nJson outputs are provided by the JsonFormatter logging formatter. You can add the custom formatter like below:\n\n**Please note: version 0.1.0 has changed the import structure, please update to the following example for proper importing**\n\n```python\n    import logging\n    from pythonjsonlogger import jsonlogger\n\n    logger = logging.getLogger()\n\n    logHandler = logging.StreamHandler()\n    formatter = jsonlogger.JsonFormatter()\n    logHandler.setFormatter(formatter)\n    logger.addHandler(logHandler)\n```\n\n## Customizing fields\n\nThe fmt parser can also be overidden if you want to have required fields that differ from the default of just `message`.\n\nThese two invocations are equivalent:\n\n```python\nclass CustomJsonFormatter(jsonlogger.JsonFormatter):\n    def parse(self):\n        return self._fmt.split(';')\n\nformatter = CustomJsonFormatter('one;two')\n\n# is equivalent to:\n\nformatter = jsonlogger.JsonFormatter('%(one)s %(two)s')\n```\n\nYou can also add extra fields to your json output by specifying a dict in place of message, as well as by specifying an `extra={}` argument.\n\nContents of these dictionaries will be added at the root level of the entry and may override basic fields.\n\nYou can also use the `add_fields` method to add to or generally normalize the set of default set of fields, it is called for every log event. For example, to unify default fields with those provided by [structlog](http://www.structlog.org/) you could do something like this:\n\n```python\nclass CustomJsonFormatter(jsonlogger.JsonFormatter):\n    def add_fields(self, log_record, record, message_dict):\n        super(CustomJsonFormatter, self).add_fields(log_record, record, message_dict)\n        if not log_record.get('timestamp'):\n            # this doesn't use record.created, so it is slightly off\n            now = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%fZ')\n            log_record['timestamp'] = now\n        if log_record.get('level'):\n            log_record['level'] = log_record['level'].upper()\n        else:\n            log_record['level'] = record.levelname\n\nformatter = CustomJsonFormatter('%(timestamp)s %(level)s %(name)s %(message)s')\n```\n\nItems added to the log record will be included in *every* log message, no matter what the format requires.\n\n## Adding custom object serialization\n\nFor custom handling of object serialization you can specify default json object translator or provide a custom encoder\n\n```python\ndef json_translate(obj):\n    if isinstance(obj, MyClass):\n        return {\"special\": obj.special}\n\nformatter = jsonlogger.JsonFormatter(json_default=json_translate,\n                                     json_encoder=json.JSONEncoder)\nlogHandler.setFormatter(formatter)\n\nlogger.info({\"special\": \"value\", \"run\": 12})\nlogger.info(\"classic message\", extra={\"special\": \"value\", \"run\": 12})\n```\n\n## Using a Config File\n\nTo use the module with a config file using the [`fileConfig` function](https://docs.python.org/3/library/logging.config.html#logging.config.fileConfig), use the class `pythonjsonlogger.jsonlogger.JsonFormatter`. Here is a sample config file.\n\n```ini\n[loggers]\nkeys = root,custom\n\n[logger_root]\nhandlers =\n\n[logger_custom]\nlevel = INFO\nhandlers = custom\nqualname = custom\n\n[handlers]\nkeys = custom\n\n[handler_custom]\nclass = StreamHandler\nlevel = INFO\nformatter = json\nargs = (sys.stdout,)\n\n[formatters]\nkeys = json\n\n[formatter_json]\nformat = %(message)s\nclass = pythonjsonlogger.jsonlogger.JsonFormatter\n```\n\nExample Output\n==============\n\nSample JSON with a full formatter (basically the log message from the unit test). Every log message will appear on 1 line like a typical logger.\n\n```json\n{\n    \"threadName\": \"MainThread\",\n    \"name\": \"root\",\n    \"thread\": 140735202359648,\n    \"created\": 1336281068.506248,\n    \"process\": 41937,\n    \"processName\": \"MainProcess\",\n    \"relativeCreated\": 9.100914001464844,\n    \"module\": \"tests\",\n    \"funcName\": \"testFormatKeys\",\n    \"levelno\": 20,\n    \"msecs\": 506.24799728393555,\n    \"pathname\": \"tests/tests.py\",\n    \"lineno\": 60,\n    \"asctime\": [\"12-05-05 22:11:08,506248\"],\n    \"message\": \"testing logging format\",\n    \"filename\": \"tests.py\",\n    \"levelname\": \"INFO\",\n    \"special\": \"value\",\n    \"run\": 12\n}\n```\n\nExternal Examples\n=================\n\n- [Wesley Tanaka - Structured log files in Python using python-json-logger](http://web.archive.org/web/20201130054012/https://wtanaka.com/node/8201)\n\n- [Archive](https://web.archive.org/web/20201130054012/https://wtanaka.com/node/8201)\n",
    "bugtrack_url": null,
    "license": "BSD",
    "summary": "A python library adding a json log formatter",
    "version": "2.0.7",
    "project_urls": {
        "Homepage": "http://github.com/madzak/python-json-logger"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "35a6145655273568ee78a581e734cf35beb9e33a370b29c5d3c8fee3744de29f",
                "md5": "618fc5f196be90261afa8372eb458f47",
                "sha256": "f380b826a991ebbe3de4d897aeec42760035ac760345e57b812938dc8b35e2bd"
            },
            "downloads": -1,
            "filename": "python_json_logger-2.0.7-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "618fc5f196be90261afa8372eb458f47",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.6",
            "size": 8067,
            "upload_time": "2023-02-21T17:40:05",
            "upload_time_iso_8601": "2023-02-21T17:40:05.117012Z",
            "url": "https://files.pythonhosted.org/packages/35/a6/145655273568ee78a581e734cf35beb9e33a370b29c5d3c8fee3744de29f/python_json_logger-2.0.7-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "4fda95963cebfc578dabd323d7263958dfb68898617912bb09327dd30e9c8d13",
                "md5": "af63a62ce9f506b2a89c0a3dadcdec61",
                "sha256": "23e7ec02d34237c5aa1e29a070193a4ea87583bb4e7f8fd06d3de8264c4b2e1c"
            },
            "downloads": -1,
            "filename": "python-json-logger-2.0.7.tar.gz",
            "has_sig": false,
            "md5_digest": "af63a62ce9f506b2a89c0a3dadcdec61",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.6",
            "size": 10508,
            "upload_time": "2023-02-21T17:40:06",
            "upload_time_iso_8601": "2023-02-21T17:40:06.209938Z",
            "url": "https://files.pythonhosted.org/packages/4f/da/95963cebfc578dabd323d7263958dfb68898617912bb09327dd30e9c8d13/python-json-logger-2.0.7.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-02-21 17:40:06",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "madzak",
    "github_project": "python-json-logger",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "tox": true,
    "lcname": "python-json-logger"
}
        
Elapsed time: 0.25234s