一组装饰器和帮助器方法,用于向应用程序添加statsd度量。
statsdecor的Python项目详细描述
体育场装饰
一组装饰器和帮助器方法,用于向应用程序添加statsd度量。
安装
您可以使用pip安装statsdecor:
pip install statsdecor
配置
必须使用statsdecor.configure
来配置内部statsd客户端
调用其他方法:
importstatsdecorstatsdecor.configure(host='localhost',prefix='superapp.')
配置通常是在应用程序引导期间设置的。一次
集合配置值在statsdecor
创建的所有客户机中重复使用。
用法
您可以使用模块函数或装饰器跟踪度量。递增 递减计数器看起来像:
度量函数
importstatsdecorstatsdecor.incr('save.succeeded')statsdecor.decr('attempts.remaining')statsdecor.gauge('sessions.active',9001)
计数器和计时器也可以通过decorators设置:
importstatsdecor.decoratorsasstats@stats.increment('save.succeeded')defsave(self):pass@stats.decrement('attempts.remaining')defattempt():pass@stats.timed('api_request.duration')defperform_request(self,req)pass
在使用decorators时,只有在修饰函数 不会引发错误。
上下文
statsdecor包括一个上下文管理器,可以帮助测量延迟和卷 同时使用度量标记对成功和失败进行分类。例如, 假设您正在调用远程服务并希望编写一个包装器 它收集延迟、容量和故障度量。
根据我们对客户机库如何指示错误的了解,我们可以创建一个上下文管理器 基于statcontext:
from statsdecor.context import StatsContext
class FoobarClientMetrics(StatsContext):
def __init__(self, tags=None):
tags = list(tags or [])
tags += ['caller:example_1']
super(ThingyStatsContext, self).__self__('thingy_client', tags=tags)
def exit_hook(self, exc_type, exc_val, exc_tb):
if exc_val is not None:
self.add_tags('result:failure')
else:
self.add_tags('result:success')
# Bonus: since we have the exception, classify the error type
if isinstance(exc_val, PermissionDenied):
self.add_tags('error:permissiondenied')
elif isinstance(exc_val, TimeOut):
self.add_tags('error:timeout')
elif exc_val is not None:
self.add_tags('error:exception')
现在使用度量编写包装函数很简单:
def foobar_get_clients(**args):
with FoobarClientMetrics(tags=['method:get_clients']) as stats:
result = call_foobar_get_client(**args)
# We know all foo methods return result['status_code'] so let's
# add a status_code tag!
stats.add_tags('status_code:{}'.format(result["status_code"]'))
return result
def foobar_add_client(**args):
with FoobarClientMetrics(tags=['method:add_client']) as stats:
result = call_foobar_add_client(**args)
stats.add_tags('status_code:{}'.format(result["status_code"]'))
return result
现在我们可以绘制图表:
- 按
method
标记分组的调用量 - 平均响应时间,不包括错误(超时将不再偏离平均值)
- 按方法和/或类型分组的错误量
开发
测试和覆盖范围
make test
make coverage
您可以使用模块函数或装饰器跟踪度量。递增
释放
statsdecor使用semver作为版本号。在标记之前, 检查自上次标记以来的所有更改,查看是否有中断更改、新功能, 和/或错误修复。
- 编辑版本
- 提交/pr/merge bump到版本
make tag