django logging set context globally per request?
django, logging, python
Solution
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
Problem
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.