python项目
py-timeexecution的Python项目详细描述
这个包的目的是将应用程序的度量记录到后端。 借助grafana您可以轻松地使用它们创建仪表板
功能
- 向多个后端发送数据
- 自定义后端
- 挂钩
后端
- 流入量b 0.8
- 弹性搜索2.1
安装
$ pip install py-timeexecution
用法
若要使用此包,请装饰要计时其执行时间的函数。 每个包装的函数都将创建一个由3个默认值组成的度量:
- 名称-度量将存储在其中的系列的名称
- 值-包装函数完成所用的时间(毫秒)
- 主机名-运行代码的计算机的主机名
请参见以下示例
fromtime_executionimportconfigure,time_executionfromtime_execution.backends.influxdbimportInfluxBackendfromtime_execution.backends.elasticsearchimportElasticsearchBackend# Setup the desired backendinflux=InfluxBackend(host='influx',database='metrics',use_udp=False)elasticsearch=ElasticsearchBackend('elasticsearch',index='metrics')# Configure the time_execution decoratorconfigure(backends=[influx,elasticsearch])# Wrap the methods where u want the metrics@time_executiondefhello():return'World'# Now when we call hello() and we will get metrics in our backendshello()
这将导致输入infloxdb
[{"name":"__main__.hello","columns":["time","sequence_number","value","hostname",],"points":[[1449739813939,1111950001,312,"machine.name",]]}]
以及elasticsearch中的以下内容
[{"_index":"metrics-2016.01.28","_type":"metric","_id":"AVKIp9DpnPWamvqEzFB3","_score":null,"_source":{"timestamp":"2016-01-28T14:34:05.416968","hostname":"dfaa4928109f","name":"__main__.hello","value":312},"sort":[1453991645416]}]
挂钩
time_execution支持挂钩,您可以在挂钩前更改度量 正在发送到后端。
使用钩子可以添加并更改现有字段。这可能是 对于希望根据以下条件向度量添加列的情况非常有用 包装函数的响应。钩子总是有3个参数:
- 响应-包装函数的返回值
- 异常-包装函数的引发异常
- metric-包含要发送到后端的数据的dict
- func_args-包装函数接收的原始参数。
- func_kwargs-包装函数接收的原始kwargs。
如果希望拆分度量,可以从钩子中更改名称。 分成多个系列。
请参阅以下示例如何设置挂钩。
# Now lets create a hookdefmy_hook(response,exception,metric,func_args,func_kwargs):status_code=getattr(response,'status_code',None)ifstatus_code:returndict(name='{}.{}'.format(metric['name'],status_code),extra_field='foo bar')# Configure the time_execution decorator, but now with hooksconfigure(backends=[backend],hooks=[my_hook])
手动发送指标
您还可以将任何手动度量发送到后端。这些不会 添加默认值,不会命中钩子。
请参见以下示例。
loadavg=os.getloadavg()write_metric('cpu.load.1m',value=loadavg[0])write_metric('cpu.load.5m',value=loadavg[1])write_metric('cpu.load.15m',value=loadavg[2])
自定义后端
编写自定义后端非常简单,只需创建一个类 使用write方法。不需要扩展baseMetricsBackend 但为了方便升级我建议你做。
fromtime_execution.backends.baseimportBaseMetricsBackendclassMetricsPrinter(BaseMetricsBackend):defwrite(self,name,**data):print(name,data)
贡献
你有什么要贡献的吗?伟大的! 一些有用的东西。
这个项目的测试是通过Docker完成的。有一个码头工人作曲很容易 启动并运行所有必需的容器。
我们经常使用一个带有几个目标的makefile:
- 进行测试
- 生成isort
- 制作绒布
- 生成
- 设置.py
所有这些make目标的前缀都可以是docker/。这将执行 目标在Docker容器中,而不是在本地计算机上。 例如生成docker/build。