Skip to main content

Adding context to log records

Project description

GitHub homepage BSD Licensed CI Status Version on PyPI

Python Logging Context

pylogctx is a library for enriching each logs records from a context. Typical usage is for adding some request_id to all logs in order to make troubleshooting more comfortable. This context is shared by all piece of code using logging, transparently.

import logging.config

from pylogctx import log_context


logging.config.dictConfig({
    'formatters': {'json': {
        '()': 'pythonjsonlogger.jsonlogger.JsonFormatter',
        'format': "%(asctime)s %(name)s %(levelname)s %(message)s",
    }},
    'filters': {'context': {
        '()': 'pylogctx.AddContextFilter',
    }},
    'handlers': {'console': {
        'class': 'logging.StreamHandler',
        'filters': ['context'],
        'formatter': 'json',
    }},
    'root': {
        'level': 'INFO',
        'handlers': ['console'],
    },
})


logger = logging.getLogger(__name__)


def mycode(request, ticket_id):
    # push new fields
    log_context.update(requestId=uuid.uuid4())
    myticket = get_object_or_404(models.Ticket, pk=ticket_id)

    # push objects, they will be adapted to log fields
    log_context.update(myticket):

    # Log as usual
    logger.info("Working on %r", myticket)

    for comment in myticket.comments:
        # A context manager allow to push and pop fields
        with log_context(comment):
            logger.info("Working on comment %r", comment)
            # code, use external libs, etc.

    # Don't forget to clear the context for the next request. Use the
    # middleware to have it clean.
    log_context.clear()

The output looks like:

{'loggerName': 'package.module', 'levelname': 'INFO', 'message': 'Working on <Ticket #1>', 'ticketId': 1, 'requestId': 'c5521138-031a-4da6-b9db-c9eda3e090f1'}
{'loggerName': 'package.module', 'levelname': 'INFO', 'message': 'Working on comment <Comment #4>', 'ticketId': 1, 'ticketCommentId': 4, 'requestId': 'c5521138-031a-4da6-b9db-c9eda3e090f1'}
{'loggerName': 'package.module', 'levelname': 'INFO', 'message': 'Working on comment <Comment #5>', 'ticketId': 1, 'ticketCommentId': 5, 'requestId': 'c5521138-031a-4da6-b9db-c9eda3e090f1'}
{'loggerName': 'package.module', 'levelname': 'INFO', 'message': 'Working on comment <Comment #78>', 'ticketId': 1, 'ticketCommentId': 78, 'requestId': 'c5521138-031a-4da6-b9db-c9eda3e090f1'}
{'loggerName': 'package.module', 'levelname': 'INFO', 'message': 'Working on comment <Comment #9>', 'ticketId': 1, 'ticketCommentId': 9, 'requestId': 'c5521138-031a-4da6-b9db-c9eda3e090f1'}
{'loggerName': 'package.module', 'levelname': 'INFO', 'message': 'Working on <Ticket #890>', 'ticketId': 890, 'requestId': 'c64aaae7-049b-4a02-929b-2d0ac9141f5c'}
{'loggerName': 'package.module', 'levelname': 'INFO', 'message': 'Working on comment <Comment #80>', 'ticketId': 890, 'ticketCommentId': 80, 'requestId': 'c64aaae7-049b-4a02-929b-2d0ac9141f5c'}

Install it with your favorite python package installer:

$ pip install pylogctx

There is a few helpers for Celery and Django projects. See USAGE for details!

Contributors

Do you want py3 support or other nice improvements ? Join us to make log rocking better!

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

pylogctx-1.3.tar.gz (5.7 kB view details)

Uploaded Source

Built Distribution

pylogctx-1.3-py2.py3-none-any.whl (7.6 kB view details)

Uploaded Python 2 Python 3

File details

Details for the file pylogctx-1.3.tar.gz.

File metadata

  • Download URL: pylogctx-1.3.tar.gz
  • Upload date:
  • Size: 5.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No

File hashes

Hashes for pylogctx-1.3.tar.gz
Algorithm Hash digest
SHA256 c974c67e187fd24da342e24223b9cce765d00facfa2c9d19ffa3e402395607f9
MD5 77aeca85a6c53546801630213e88ae38
BLAKE2b-256 ffc74bb049bce63fb9a47ab13d2cd3214e2e94237d4c20b45deb0d4ee492ea03

See more details on using hashes here.

File details

Details for the file pylogctx-1.3-py2.py3-none-any.whl.

File metadata

File hashes

Hashes for pylogctx-1.3-py2.py3-none-any.whl
Algorithm Hash digest
SHA256 808d6468a27e3452f2c03bef2e73848d1bd1fcaecadf954cb3b94f9bf349312a
MD5 36a162f029701849f12ab68f3fb46343
BLAKE2b-256 d3cd99f698a155928f877268bff678f8668ba59583c3f54da02309ac633bcfc0

See more details on using hashes here.

Supported by

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