Lets say I want to log like this formatting string :
%(levelname)s %(asctime)s %(module)s %(funcName)s %(message)s %(user_id)
It can be done using this type of logging command :
logging.error('Error fetching information', extra = { 'user_id': 22 } )
This will add the current userid to logging messages for current request.
But the extra dict needs to be added to every logging call.
Is there a good way to add this context in a common function in django (eg Middleware, or index function of a view ), so that the extra dictionary with user id is set, and all further logging calls in the current request also log the current user.
There exists a ThreadLocal middleware on https://github.com/jedie/django-tools/blob/master/django_tools/middlewares/ThreadLocal.py which helps you with your issue in making the current request available everywhere.
So what you need to do is add the middleware to your MIDDLEWARE_CLASSES setting, and create a function somewhere like this:
from django_tools.middlewares import ThreadLocal def log_something(levelname, module, funcname, message): user = ThreadLocal.get_current_user() # do your logging here. "user" is the user object and the user id is in user.pk
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With