我在爲我的tastypie restfull應用程序創建訪問記錄器時遇到問題。 我想在服務器的請求中記錄多個HTTP頭,並將它們傳遞給在django設置文件中定義的記錄器/處理程序。這個想法是將每個HTTP請求記錄到訪問日誌文件中。記錄Tastypie請求(訪問日誌)
我遇到了幾個日誌模塊(應用程序),但他們都使用數據庫,我希望更簡單的基本訪問日誌。
我在爲我的tastypie restfull應用程序創建訪問記錄器時遇到問題。 我想在服務器的請求中記錄多個HTTP頭,並將它們傳遞給在django設置文件中定義的記錄器/處理程序。這個想法是將每個HTTP請求記錄到訪問日誌文件中。記錄Tastypie請求(訪問日誌)
我遇到了幾個日誌模塊(應用程序),但他們都使用數據庫,我希望更簡單的基本訪問日誌。
最後我使我自己的中間件類中的應用程序根middleware.py。
另外我在Settings.py中間件部分放置了'appname.middleware.RequestLoggerMiddleware',
。
這裏是我的訪問日誌記錄中間件類的代碼:
import logging
logger = logging.getLogger('access')
class RequestLoggerMiddleware(object):
def process_request(self, request):
... logging logic here...
logger.info('logging message'))
return None
欲瞭解更多信息有關中間件組件看到Django Middleware documentation。
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)
另一種可能性是覆蓋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
它可能是一個代理服務器,但是我在request.META ['USER']'上得到一個KeyError' – mlissner
但我沒有任何意見......我只是用資源從Tastypie。擴展現有類是唯一的解決方案嗎? – lpandzic
我認爲我需要做的就是實現自己的中間件(https://docs.djangoproject.com/zh/dev/topics/http/middleware/?from=olddocs),process_request返回None。 – lpandzic