pylogrus


Namepylogrus JSON
Version 0.4.0 PyPI version JSON
download
home_pagehttps://github.com/vmig/pylogrus
SummaryPyLogrus is a structured logger for Python
upload_time2018-06-24 13:55:54
maintainer
docs_urlNone
authorVitalii Myhal
requires_python
licenseMIT License
keywords logger logging colorize output json extra fields
VCS
bugtrack_url
requirements six
Travis-CI No Travis.
coveralls test coverage No coveralls.
            
PyLogrus
========

PyLogrus is a structured logger for Python which is inspired by Logrus
Golang library https://github.com/sirupsen/logrus. PyLogrus extends the
built-in ``logging`` module with the ability making a colorized records
in log and records in JSON format.

Features
--------

Using this package, you will be able to:

-  colorize output in console (Textual format)
-  switch off the colorization (Textual format)
-  add extra fields in a log record
-  add permanent extra fields in a log record
-  add permanent prefix for message
-  create a new contextual instance
-  save log records in the JSON format
-  override the names of logging levels
-  override colors of base elements (Textual format)
-  override name of keys (JSON format)
-  define only needed fields in records (JSON format)
-  create time of a record in Zulu format

.. figure:: https://github.com/vmig/pylogrus/blob/master/examples/screenshot.png?raw=true
   :alt: Colored


Initialization
--------------

.. code:: python

    import logging
    from pylogrus import PyLogrus

    logging.setLoggerClass(PyLogrus)


Formatters
----------

TextFormatter
~~~~~~~~~~~~~
TextFormatter class allows colorizing console output by setting a
``colorize`` argument. The colorization can be switched off. Time of log
record may be set in Zulu format. Just set ``datefmt`` argument as 'Z'.

.. code:: python

    import logging
    from pylogrus import PyLogrus, TextFormatter

    logging.setLoggerClass(PyLogrus)

    logger = logging.getLogger(__name__)  # type: PyLogrus
    logger.setLevel(logging.DEBUG)

    formatter = TextFormatter(datefmt='Z', colorize=True)

    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)
    ch.setFormatter(formatter)
    logger.addHandler(ch)


Overriding name of levels
^^^^^^^^^^^^^^^^^^^^^^^^^
You can define only necessary changes:

.. code:: python

    formatter = TextFormatter(datefmt='Z', colorize=True)
    formatter.override_level_names({'CRITICAL': 'CRIT', 'ERROR': 'ERRO', 'WARNING': 'WARN', 'DEBUG': 'DEBU'})

or for instance:

.. code:: python

    formatter.override_level_names({'CRITICAL': 'FATAL'})


Overriding colors
^^^^^^^^^^^^^^^^^
TextFormatter has several base elements which can be colorized. You can
get them via ``color`` property:

::

    print(formatter.color)
    ...
    {
        'asctime':  '\x1b[2;37m',  # time of log record
        'prefix':   '\x1b[0;36m',  # message prefix
        'field':    '\x1b[0;32m',  # key of extra field
        'value':    '\x1b[0m',     # value of extra field
        'debug':    '\x1b[0;34m',
        'info':     '\x1b[0;32m',
        'warning':  '\x1b[0;33m',
        'error':    '\x1b[0;31m',
        'critical': '\x1b[2;31m'
    }

A color of elements can be changed using CL\_\* constants. You can
define new color only for those elements you need.

.. code:: python

    from pylogrus import PyLogrus, TextFormatter, CL_BLDYLW
    ...
    formatter = TextFormatter(colorize=True)
    formatter.override_colors({'prefix': CL_BLDYLW})


JsonFormatter
~~~~~~~~~~~~~
JsonFormatter class allows to save log records in the JSON format.
During class initialization, you can:

-  Set time of log record in Zulu format. Just set ``datefmt`` argument
   as 'Z'.
-  Define a list of enabled fields which will be present in a log record
   via ``enabled_fields`` argument. An enabled field is represented by
   original field name or by a tuple which contains the original name
   and new desirable name. The new name overrides the original one in an
   output.
-  For pretty print a JSON log record in a console, set the ``indent``
   and ``sort_keys`` arguments (optional).

.. code:: python

    import logging
    from pylogrus import PyLogrus, JsonFormatter

    logging.setLoggerClass(PyLogrus)

    logger = logging.getLogger(__name__)  # type: PyLogrus
    logger.setLevel(logging.DEBUG)

    enabled_fields = [
        ('name', 'logger_name'),
        ('asctime', 'service_timestamp'),
        ('levelname', 'level'),
        ('threadName', 'thread_name'),
        'message',
        ('exception', 'exception_class'),
        ('stacktrace', 'stack_trace'),
        'module',
        ('funcName', 'function')
    ]

    formatter = JsonFormatter(datefmt='Z', enabled_fields=enabled_fields, indent=2, sort_keys=True)

    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)
    ch.setFormatter(formatter)
    logger.addHandler(ch)


Overriding name of levels
^^^^^^^^^^^^^^^^^^^^^^^^^
Name of levels can be overridden in the same way as in case of using the
TextFormatter.

.. code:: python

    formatter = JsonFormatter()
    formatter.override_level_names({'WARNING': 'WARN'})


Usage
-----
Please, see the examples of usage in the ``examples`` directory.

Log message as usual:

.. code:: python

    import logging
    from pylogrus import PyLogrus, TextFormatter

    def get_logger():
        logging.setLoggerClass(PyLogrus)
        ...
        formatter = TextFormatter()
        ...
        return logger

    log = get_logger()
    log.debug("Using base logger")

Log message with an extra field:

.. code:: python

    log.withFields({'user': 'John Doe'}).debug("Message with an extra field")

Add permanent field(s) in logger and get a contextual instance:

.. code:: python

    log_ctx = log.withFields({'context': 1})
    log_ctx.info("Add permanent field into current logger")

Add permanent prefix to message for current logger instance:

.. code:: python

    log_ctx = log_ctx.withPrefix("[API]")
    log_ctx.info("Add prefix as a permanent part of a message")

Log message with extra fields:

.. code:: python

    log_ctx.withFields({
        'user': 'Admin',
        'transaction_id': str(uuid.uuid4())
    }).warning("Message with prefix and extra fields")



            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/vmig/pylogrus",
    "name": "pylogrus",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "",
    "maintainer_email": "",
    "keywords": "logger logging colorize output json extra fields",
    "author": "Vitalii Myhal",
    "author_email": "6934861+vmig@users.noreply.github.com",
    "download_url": "https://files.pythonhosted.org/packages/ca/ae/cf2c880abe69abfd9c5e49922e789f5628b3c598c697be7bb91068743dcd/pylogrus-0.4.0.tar.gz",
    "platform": "",
    "description": "\nPyLogrus\n========\n\nPyLogrus is a structured logger for Python which is inspired by Logrus\nGolang library https://github.com/sirupsen/logrus. PyLogrus extends the\nbuilt-in ``logging`` module with the ability making a colorized records\nin log and records in JSON format.\n\nFeatures\n--------\n\nUsing this package, you will be able to:\n\n-  colorize output in console (Textual format)\n-  switch off the colorization (Textual format)\n-  add extra fields in a log record\n-  add permanent extra fields in a log record\n-  add permanent prefix for message\n-  create a new contextual instance\n-  save log records in the JSON format\n-  override the names of logging levels\n-  override colors of base elements (Textual format)\n-  override name of keys (JSON format)\n-  define only needed fields in records (JSON format)\n-  create time of a record in Zulu format\n\n.. figure:: https://github.com/vmig/pylogrus/blob/master/examples/screenshot.png?raw=true\n   :alt: Colored\n\n\nInitialization\n--------------\n\n.. code:: python\n\n    import logging\n    from pylogrus import PyLogrus\n\n    logging.setLoggerClass(PyLogrus)\n\n\nFormatters\n----------\n\nTextFormatter\n~~~~~~~~~~~~~\nTextFormatter class allows colorizing console output by setting a\n``colorize`` argument. The colorization can be switched off. Time of log\nrecord may be set in Zulu format. Just set ``datefmt`` argument as 'Z'.\n\n.. code:: python\n\n    import logging\n    from pylogrus import PyLogrus, TextFormatter\n\n    logging.setLoggerClass(PyLogrus)\n\n    logger = logging.getLogger(__name__)  # type: PyLogrus\n    logger.setLevel(logging.DEBUG)\n\n    formatter = TextFormatter(datefmt='Z', colorize=True)\n\n    ch = logging.StreamHandler()\n    ch.setLevel(logging.DEBUG)\n    ch.setFormatter(formatter)\n    logger.addHandler(ch)\n\n\nOverriding name of levels\n^^^^^^^^^^^^^^^^^^^^^^^^^\nYou can define only necessary changes:\n\n.. code:: python\n\n    formatter = TextFormatter(datefmt='Z', colorize=True)\n    formatter.override_level_names({'CRITICAL': 'CRIT', 'ERROR': 'ERRO', 'WARNING': 'WARN', 'DEBUG': 'DEBU'})\n\nor for instance:\n\n.. code:: python\n\n    formatter.override_level_names({'CRITICAL': 'FATAL'})\n\n\nOverriding colors\n^^^^^^^^^^^^^^^^^\nTextFormatter has several base elements which can be colorized. You can\nget them via ``color`` property:\n\n::\n\n    print(formatter.color)\n    ...\n    {\n        'asctime':  '\\x1b[2;37m',  # time of log record\n        'prefix':   '\\x1b[0;36m',  # message prefix\n        'field':    '\\x1b[0;32m',  # key of extra field\n        'value':    '\\x1b[0m',     # value of extra field\n        'debug':    '\\x1b[0;34m',\n        'info':     '\\x1b[0;32m',\n        'warning':  '\\x1b[0;33m',\n        'error':    '\\x1b[0;31m',\n        'critical': '\\x1b[2;31m'\n    }\n\nA color of elements can be changed using CL\\_\\* constants. You can\ndefine new color only for those elements you need.\n\n.. code:: python\n\n    from pylogrus import PyLogrus, TextFormatter, CL_BLDYLW\n    ...\n    formatter = TextFormatter(colorize=True)\n    formatter.override_colors({'prefix': CL_BLDYLW})\n\n\nJsonFormatter\n~~~~~~~~~~~~~\nJsonFormatter class allows to save log records in the JSON format.\nDuring class initialization, you can:\n\n-  Set time of log record in Zulu format. Just set ``datefmt`` argument\n   as 'Z'.\n-  Define a list of enabled fields which will be present in a log record\n   via ``enabled_fields`` argument. An enabled field is represented by\n   original field name or by a tuple which contains the original name\n   and new desirable name. The new name overrides the original one in an\n   output.\n-  For pretty print a JSON log record in a console, set the ``indent``\n   and ``sort_keys`` arguments (optional).\n\n.. code:: python\n\n    import logging\n    from pylogrus import PyLogrus, JsonFormatter\n\n    logging.setLoggerClass(PyLogrus)\n\n    logger = logging.getLogger(__name__)  # type: PyLogrus\n    logger.setLevel(logging.DEBUG)\n\n    enabled_fields = [\n        ('name', 'logger_name'),\n        ('asctime', 'service_timestamp'),\n        ('levelname', 'level'),\n        ('threadName', 'thread_name'),\n        'message',\n        ('exception', 'exception_class'),\n        ('stacktrace', 'stack_trace'),\n        'module',\n        ('funcName', 'function')\n    ]\n\n    formatter = JsonFormatter(datefmt='Z', enabled_fields=enabled_fields, indent=2, sort_keys=True)\n\n    ch = logging.StreamHandler()\n    ch.setLevel(logging.DEBUG)\n    ch.setFormatter(formatter)\n    logger.addHandler(ch)\n\n\nOverriding name of levels\n^^^^^^^^^^^^^^^^^^^^^^^^^\nName of levels can be overridden in the same way as in case of using the\nTextFormatter.\n\n.. code:: python\n\n    formatter = JsonFormatter()\n    formatter.override_level_names({'WARNING': 'WARN'})\n\n\nUsage\n-----\nPlease, see the examples of usage in the ``examples`` directory.\n\nLog message as usual:\n\n.. code:: python\n\n    import logging\n    from pylogrus import PyLogrus, TextFormatter\n\n    def get_logger():\n        logging.setLoggerClass(PyLogrus)\n        ...\n        formatter = TextFormatter()\n        ...\n        return logger\n\n    log = get_logger()\n    log.debug(\"Using base logger\")\n\nLog message with an extra field:\n\n.. code:: python\n\n    log.withFields({'user': 'John Doe'}).debug(\"Message with an extra field\")\n\nAdd permanent field(s) in logger and get a contextual instance:\n\n.. code:: python\n\n    log_ctx = log.withFields({'context': 1})\n    log_ctx.info(\"Add permanent field into current logger\")\n\nAdd permanent prefix to message for current logger instance:\n\n.. code:: python\n\n    log_ctx = log_ctx.withPrefix(\"[API]\")\n    log_ctx.info(\"Add prefix as a permanent part of a message\")\n\nLog message with extra fields:\n\n.. code:: python\n\n    log_ctx.withFields({\n        'user': 'Admin',\n        'transaction_id': str(uuid.uuid4())\n    }).warning(\"Message with prefix and extra fields\")\n\n\n",
    "bugtrack_url": null,
    "license": "MIT License",
    "summary": "PyLogrus is a structured logger for Python",
    "version": "0.4.0",
    "project_urls": {
        "Homepage": "https://github.com/vmig/pylogrus"
    },
    "split_keywords": [
        "logger",
        "logging",
        "colorize",
        "output",
        "json",
        "extra",
        "fields"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "0a1e442607ebf6d6f3e6f32d10c1f280ca43336ca8aaad308008b91d3d386488",
                "md5": "a52ad8d8a593e002856b5cc0d1bb2747",
                "sha256": "4458910a5da8f313a6ff1e09dace69a93147736caad31724dbb9ff464369ea3b"
            },
            "downloads": -1,
            "filename": "pylogrus-0.4.0-py2.py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "a52ad8d8a593e002856b5cc0d1bb2747",
            "packagetype": "bdist_wheel",
            "python_version": "py2.py3",
            "requires_python": null,
            "size": 11610,
            "upload_time": "2018-06-24T13:55:52",
            "upload_time_iso_8601": "2018-06-24T13:55:52.488791Z",
            "url": "https://files.pythonhosted.org/packages/0a/1e/442607ebf6d6f3e6f32d10c1f280ca43336ca8aaad308008b91d3d386488/pylogrus-0.4.0-py2.py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "caaecf2c880abe69abfd9c5e49922e789f5628b3c598c697be7bb91068743dcd",
                "md5": "db8a897d40b71910a6295451ade1a359",
                "sha256": "13db3a7b28f185d6b0b703be6c71fc612c271da92eb49753ab487dcf56299358"
            },
            "downloads": -1,
            "filename": "pylogrus-0.4.0.tar.gz",
            "has_sig": false,
            "md5_digest": "db8a897d40b71910a6295451ade1a359",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 10616,
            "upload_time": "2018-06-24T13:55:54",
            "upload_time_iso_8601": "2018-06-24T13:55:54.157146Z",
            "url": "https://files.pythonhosted.org/packages/ca/ae/cf2c880abe69abfd9c5e49922e789f5628b3c598c697be7bb91068743dcd/pylogrus-0.4.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2018-06-24 13:55:54",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "vmig",
    "github_project": "pylogrus",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "requirements": [
        {
            "name": "six",
            "specs": [
                [
                    ">=",
                    "1.10"
                ]
            ]
        }
    ],
    "tox": true,
    "lcname": "pylogrus"
}
        
Elapsed time: 0.21079s