Django请求弹性搜索日志
drel的Python项目详细描述
DREL
Django请求弹性搜索日志记录
django支持
要记录每个django请求,请在AuthenticationMiddleware之前插入LoggingMiddleware:
# settings.pyMIDDLEWARE=[...,"django.contrib.auth.middleware.AuthenticationMiddleware","drel.django.LoggingMiddleware",...]
这将以以下格式向名为logs-{week_start}-{week_end}
的弹性搜索索引插入请求和响应信息:
{"timestamp":"2018-12-09 02:22:22","type":"default","request":{"url":"https://httpbin.org/post","data":{"param1":"value1"},"headers":{}},"response":{"status":200,"data":{"args":{},"data":"","files":{},"form":{"param1":"value1"},"headers":{"Accept":"*/*","Accept-Encoding":"gzip, deflate","Connection":"close","Content-Length":"13","Content-Type":"application/x-www-form-urlencoded","Host":"httpbin.org","User-Agent":"python-requests/2.19.1"},"json":null,"origin":"130.193.67.76","url":"https://httpbin.org/post"}},"app":"default","request_id":"2180930f-859b-4aef-8770-17107fff1170"}
请求支持
要记录requests请求和响应数据,请使用drel.requests.log
函数:
>>> from drel.requests import post, log >>> request, response = post("https://httpbin.org/post", {"param1": "value1"}) >>> log(request, response)
配置
更改设置覆盖config
模块值:
fromdrelimportconfigconfig.APPLICATION="django_app"
django配置示例
fromdjango.httpimportHttpRequestfromdrel.coreimportconfigfromdrel.djangoimportmail_admins_on_es_exceptiondefignore_logging_handler(request:HttpRequest)->bool:returnany([request.path=="/api/register_device/",request.method!="POST",])config.ELASTIC_SEARCH_EXCEPTION_HANDLER=mail_admins_on_es_exceptionconfig.INDEX_NAME_GETTER=lambda:"django_app_2019-01-01"config.APPLICATION="django_app"config.IGNORE_LOGGING_HANDLER=ignore_logging_handler
此配置:
- 弹性搜索索引异常时的邮件管理员
- 忽略记录非POST和/API/注册设备/请求
- 将文档插入django_app_2019-01-01索引
- 应用程序字段=django_app