python - django logging set context globally per request? -


lets want log formatting string :

%(levelname)s %(asctime)s %(module)s %(funcname)s %(message)s %(user_id) 

it can done using type of logging command :

logging.error('error fetching information', = { 'user_id': 22 } )

this add current userid logging messages current request.

but dict needs added every logging call.

is there way add context in common function in django (eg middleware, or index function of view ), dictionary user id set, , further logging calls in current request log current user.

there exists threadlocal middleware on https://github.com/jedie/django-tools/blob/master/django_tools/middlewares/threadlocal.py helps issue in making current request available everywhere.

so need add middleware middleware_classes setting, , create function somewhere this:

 django_tools.middlewares import threadlocal  def log_something(levelname, module, funcname, message):      user = threadlocal.get_current_user()      # logging here. "user" user object , user id in user.pk 

Popular posts from this blog

How to calculate SNR of signals in MATLAB? -

java - How to create Table using Apache PDFBox -

mpi - Why is MPI_Bsend not returning error even when the buffer is insufficient to accommodate all the messages -