django logging - django.request logger and extra context

梦想与她 提交于 2019-12-04 18:07:41

问题


Am on django 1.3., python 2.6

In the django docs here
https://docs.djangoproject.com/en/1.3/topics/logging/#django-request
it says that messages have the following extra context: status and request.
How do you get these to show up in the debug file? i tried in my logging config something like:

'formatters': {        
        'simple_debug': {
            'format': '[%(asctime)s] %(levelname)s %(module)s %(message)s %(request.user)s',        
        }
    },

but that causes the overall logging to fail (i.e. no logging output happens)


EDIT: So immediately after submitting the question i came across this: http://groups.google.com/group/django-users/browse_thread/thread/af682beb1e4af7f6/ace3338348e92a21

can someone help explain/elaborate on

All the quote from the docs really means is that all the places inside of django where django.request is used, the request is explicitly passed in as part of extra.

where is request explicitly passed in as part of extra to?


回答1:


You can't use request.user in the format string, as %-formatting doesn't handle that. You could use a format string such as

'[%(asctime)s] %(levelname)s %(module)s %(message)s %(user)s'

and, in your logging call, use something like

logger.debug('My message with %s', 'args', extra={'user': request.user})

The extra dict is merged into the logging event record, which ends up with a user attribute, and this then gets picked up through the format string and appears in the log.

If using the django.request logger, the status_code and the request will be passed in the extra dict by Django. If you need the request.user, you'll probably need to add a logging.Filter which does something like:

class RequestUserFilter(logging.Filter):
    def filter(self, record):
        record.user = record.request.user
        return True

so that you can show the user in the formatted output.




回答2:


The django-requestlogging middleware plugin makes it easy to log request-related information without adjusting all your logging calls to add the request with the extra parameter. It's then just a matter of configuring your loggers.

The following items can be logged when using django-requestlogging:

  • username
  • http_user_agent
  • path_info
  • remote_add
  • request_method
  • server_protocol


来源:https://stackoverflow.com/questions/10292082/django-logging-django-request-logger-and-extra-context

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!