Skip to main content
Pre-release

This release is a pre-release and may not be stable for production use.

LogExtraCtx

This small humble library is for making logging extra parameters in logging a bit easier.

Rationale

I have blognote about it.

Usage

(look also into docstrings of modules and classes)

Pure python

Use getLogger from logextractx.logger, and then create local logger with local context:

from logextractx.logger import getLogger
logger = getLogger(__name__)
[...]
loclogger = logger.local(extra={'DATA_IN': 'CURRENT_CONTEXT'})

Eg:

from logextractx.logger import getLogger
logger = getLogger(__name__)


def send_message(environment: str, requester: str, recipient: str, text: str) -> bool:
    """ Function send_message sends MSG to the specified recipient.  """

    # extra data to be indexed
    loclogger = logger.local(extra={'ACTION_TYPE': 'SEND_MSG',
                                    'requester': requester,
                                    'recipient': recipient,
                                    'user': str(request.user),
                                    'environment': env_type})

    try:
        r = requests.post(settings.MSG_PROVIDER, json={'recipient': recipient, 'content': text},
                          ... < other params > ....)
        r.raise_for_status()
    except requests.exceptions.RequestException as e:
        loclogger.error('Sending MSG failed. Response text: "%s"', e)
        loclogger.debug("headers=%r", r.result.headers)
        return False
    loclogger.info('Sending MSG success.')
    return True

Django

To tie all log records with common request-id and session-id, do the following:

  • append logextractx.middleware.LogCtxDjangoMiddleware to your MIDDLEWARE in settings:
MIDDLEWARE = [
    [...]
     'django.contrib.sessions.middleware.SessionMiddleware',
    [...]
    'logextractx.middleware.LogCtxDjangoMiddleware',
 ]

And instead of logextractx.logger use logextractx.middleware so:

from logextractx.logger import getLogger
logger = getLogger(__name__)
[...]

Also, you need to add filter into logging

    'filters': {
        'RidFilter': {
            '()': 'logextractx.middleware.RidFilter'
        }
    }

And that's all. Now every log entry will contain request_id and session_id fields.

Django + DjHuey

If you want to also pass request/session-id to working Huey/DjHuey by such modifications:

Instead

from huey.contrib.djhuey import db_periodic_task, db_task, task

you should use

from logextractx.djhuey import db_periodic_task, db_task, task

If you do so, then all extra context, including request-id and session-id will be passed to logger on the Djhuey side.

Flask

LogExtraCtx in Flask is quite similar to usage in Django:

from logextractx.flask import init_logctx
from logextractx.middleware import getLogger
[...]

app = flask.Flask(__name__)
app.secret_key = "don't tell anyone"
init_logctx(app)

[...]

logger = getLogger(__name__)

Extra Formatter

If you use plain logging format, you may be interested in using logextractx.formatter.ExtraFormatter. Just add following in your formatter definition (DictConfig):

        'formatters': {
            'simple': {
                '()': 'logextractx.formatter.ExtraFormatter',
                'fmt': '%(levelname)s %(asctime)s %(name)s: %(message)s [%(extras)s]'
            }
        }

And then you will have all extra in single log line.

License:

Licensed under the Apache License, Version 2.0

Metadata

Release files for logextractx 0.3.0rc4

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for logextractx 0.3.0rc4
File Size Uploaded Provenance Actions
logextractx-0.3.0rc4.tar.gz 13.8 kB Without provenance Details for logextractx-0.3.0rc4.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for logextractx 0.3.0rc4
File Interpreter ABI Platform Actions
logextractx-0.3.0rc4-py3-none-any.whl Python 3 none any Details for logextractx-0.3.0rc4-py3-none-any.whl

Total release size: 29.5 kB

Release files / logextractx-0.3.0rc4.tar.gz

Download URL logextractx-0.3.0rc4.tar.gz
Size 13.8 kB
Tags Source
SHA-256 checksum
How to use checksums
e5aca378dad921736bf61cc56be5720b995e63d46f7a442bc282e69c8e605ea2
BLAKE2b-256 checksum
How to use checksums
d0c7755b709044a72c679147626165adb899bec6ac12a9074b2187341f8d52b6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.4.2 importlib_metadata/4.8.1 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.10.0

Release files / logextractx-0.3.0rc4-py3-none-any.whl

Download URL logextractx-0.3.0rc4-py3-none-any.whl
Size 15.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
f13c5291d1aa7db64002f1f636c1e4c785cc4685587dbb9714fb005fadb2ccf1
BLAKE2b-256 checksum
How to use checksums
f2c765b2a2288ebe0cf8fed424a76a64ebd260fb446189bc0a17f4d5d959fbb2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.4.2 importlib_metadata/4.8.1 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.10.0

Security for logextractx 0.3.0rc4

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page