3

我在为我的 sweetpie restfull 应用程序创建访问记录器时遇到问题。我想在对服务器的请求中记录几个 HTTP 标头,并将它们传递给 django 设置文件中定义的记录器/处理程序。这个想法是将每个 HTTP 请求记录到访问日志文件中。

我遇到了几个日志模块(应用程序),但它们都使用数据库,我想要一些更简单的基本访问日志。

4

3 回答 3

3

我最终在应用程序根目录中的 middleware.py 中创建了自己的中间件类。

我也放在'appname.middleware.RequestLoggerMiddleware',Settings.py Middleware 部分。

这是我的访问日志中间件类的代码:

import logging

logger = logging.getLogger('access')

class RequestLoggerMiddleware(object):
    def process_request(self, request):
        ... logging logic here...

        logger.info('logging message'))
        return None

有关中间件组件的更多信息,请参阅Django 中间件文档

于 2012-11-20T13:00:07.110 回答
1

另一种可能性是在自定义对象中覆盖该ModelResource.dispatch()方法:ModelResource

class CustomModelResource(ModelResource):
    def dispatch(self, request_type, request, **kwargs):
        """
        Override for systematic logging.
        """
        log_user = request.META['USER']
        log_request_type = request_type
        log_resource_name = kwargs['resource_name']
        log_api_name = kwargs['api_name']
        log_response = {}

        try:
            response = super(CustomModelResource, self).dispatch(request_type, request, **kwargs)
            log_response['response_code'] = response.status_code
        # Also log what could go wrong
        except Exception, e:
            log_response['error_type'] = e.__class__.__name__
            log_response['error_message'] = e.message
            log_response['response_code'] = http.HttpBadRequest.status_code
            raise
        finally:
            # Log all the things
            logger.debug('%s asked for %s on %s through api %s: \n%s' % (
                log_user,
                log_request_type,
                log_resource_name,
                log_api_name,
                log_response,
            ))

        return response

class Meta:
    # Other custom stuff
于 2014-09-04T16:59:53.307 回答
-3
import logging


logger = logging.getLogger('project.app.view')


def my_view(request):
    entry = '%s %s for %s' % (request.method, request.get_full_path(), request.META['REMOTE_ADDR'])
    logger.info(entry)

请参阅https://docs.djangoproject.com/en/1.4/topics/logging/

于 2012-11-19T20:04:56.750 回答