Alex Rivera | Logout

django logging set context globally per request?

Asked 2013-04-25T08:38:38.707
23

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.

Edit
Report

1 Answer

1

I think you are looking for a custom log formatter. Taken in conjunction with mawimawi's answer to include the threadlocal information, your format method could automatically take the information and add it to each logged message.

There are a couple of things to think about: First, threadlocal variables can be dangerous and, worse, leak information, if you deploy in a way that uses a threadpool. Second, you need to be cautious how you write your formatter in case it gets called in a context that doesn't have the threadlocal information.

answered 2013-05-27T01:15:36.203

Your Answer