LoggerAdapter, which helps you to propagate context information
Project description
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.LogCtxDjangoMiddlewareto yourMIDDLEWAREin 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
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file logextractx-0.3.0rc3.tar.gz.
File metadata
- Download URL: logextractx-0.3.0rc3.tar.gz
- Upload date:
- Size: 13.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/3.4.1 importlib_metadata/4.5.0 pkginfo/1.7.0 requests/2.25.1 requests-toolbelt/0.9.1 tqdm/4.61.1 CPython/3.9.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
bc26199020b68afd4ff61783589abd069cf03c494c6701cdb1a04d07ea37f348
|
|
| MD5 |
f36ebcd32a57363ab6b80983972b2754
|
|
| BLAKE2b-256 |
cba203fd7be3775e685ca181806d7a80bfe1b807ffea4e45429849e8385c1acb
|
File details
Details for the file logextractx-0.3.0rc3-py3-none-any.whl.
File metadata
- Download URL: logextractx-0.3.0rc3-py3-none-any.whl
- Upload date:
- Size: 15.5 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/3.4.1 importlib_metadata/4.5.0 pkginfo/1.7.0 requests/2.25.1 requests-toolbelt/0.9.1 tqdm/4.61.1 CPython/3.9.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
6d626227fc18d6aa0e3a3ce0972327cfa7192a8cedf368a3a5e0e774e41f1576
|
|
| MD5 |
897e9e8a0fe40cd5fd4c4e876c636b6f
|
|
| BLAKE2b-256 |
118cf5324df84abc3a22e37aa7ce2be28bfecacbd2f5f7a74e03152cc8344eb0
|