通过批量上传将操作记录到弹性搜索
bes的Python项目详细描述
BES是Elastic Search的一个灵活的bulk uploader。在 现在,它只支持索引上传over UDP。你可以找回 弹性搜索的日志数据及其动态分析 Kibana(source)。这个包只是将初始上传到 弹性搜索尽可能无痛。
存储连接参数和其他配置选项 在bes.DEFAULT中。根据需要覆盖它们(例如连接到 远程弹性搜索服务器):
>>> import bes >>> bes.DEFAULT['host'] = 'my-es-server.example.com'
然后注销:
>>> bes.log(type='record', user='jdoe', action='swims')
如果您愿意,可以重写 每次通话:
>>> bes.log(index='my-index', type='my-type', user='jdoe', action='bikes')
上面生成的日志将如下所示:
{ "@timestamp": "2013-09-26T16:34:09.179048", "@version": 1, "action": "bikes", "user": "jdoe" }
跟随乔丹·西塞尔的new format为Logstash:
您应该为创建的每个记录指定唯一的type,因为 弹性搜索不会重新计算它的mapping如果你发布了一个新的 使用具有新数据类型的旧密钥的事件。如果你只是 记录单个记录类型时,可以配置全局默认值:
>>> bes.DEFAULT['type'] = 'record' >>> bes.log(user='jdoe', action='runs')
django
尽管库的核心是框架不可知的,但是我们将使用 这将在Django网站中记录事件。有几个帮手 从HttpRequest中提取信息,使之与 可能的。把它放进你的views里,像这样:
import django.http imort django.shortcuts import bes.django from polls.models import Poll def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: bes.django.log_user_request_path( request=request, type='404', poll_id=poll_id) raise django.http.Http404 bes.django.log_user_request_path( request=request, type='poll-detail', poll_id=poll_id, poll_name=p.name) return django.shortcutsrender_to_response( 'polls/detail.html', {'poll': p})
您还可以在django配置中覆盖bes的默认值:
BULK_ELASTIC_SEARCH_LOGGING_HOST = 'my-es-server.example.com'
django配置名将大写的DEFAULT键与 BULK_ELASTIC_SEARCH_LOGGING_前缀(例如,host→ BULK_ELASTIC_SEARCH_LOGGING_HOST)。
跟踪
要记录关键函数的活动,BES有跟踪修饰符:
import bes.trace @bes.trace.trace() def my_function(): return 1 + 2 / 3
默认情况下,使用修饰函数的 名称(例如my_function)作为日志类型。如果 你想要不同的东西:
def my_logger(*args, **kwargs): print((args, kwargs)) @bes.trace.trace(type='my-type', logger=my_logger) def my_function(): return 1 + 2 / 3
附加的trace参数直接传递给 记录器:
@bes.trace.trace(index='my-index', type='my-type', sport='triathalon') def my_function(): return 1 + 2 / 3
默认情况下,在修饰 函数在完成后或引发异常时启动。一个 action参数在每种情况下都传递给记录器,值为 分别为start、complete和error。在错误中 case,记录器还传递字符串化异常 (error=str(e))帮助调试问题。如果你不知道 如果需要这些记录的消息中的一条或多条,可以将其关闭:
@bes.trace.trace(start=False, error=False, complete=False): def my_function(): return 1 + 2 / 3
不过,如果你把它们都关掉,你就什么也得不到 消息;)。
跟踪装饰器使用wrapt(如果已安装)来创建 内省保存装饰。如果没有安装wrapt,我们 回退到内置的functools.wraps来处理基本的 像docstrings,但对于更多的参与 内省(例如inspect.getsource)。
测试
测试使用unittest的automatic test discovery。运行测试 套房配有:
$ python -m unittest discover
对于python<;3.3,测试套件需要外部的mock包, 在python 3.3中作为unittest.mock绑定。