如何使用 GCP Monitoring 从 python3 个应用记录自定义性能指标

How to record custom performance metrics with GCP Monitoring from python3 apps

我正在研究可以添加到 python 方法的装饰器,这些方法将指标发送到 GCP 监控。该方法已确认,但如果我尝试发送超过 1 个观察结果,API 推送指标的调用将失败。该模式是在流程完成后收集指标并刷新,以保持此测试的简单性。捕获指标内联的代码在这里:

    def append(self, value):
        now = time.time()
        seconds = int(now)
        nanos = int((now - seconds) * 10 ** 9)
        interval = monitoring_v3.TimeInterval(
            {"end_time": {"seconds": seconds, "nanos": nanos}}
        )
        point = monitoring_v3.Point({
            "interval": interval,
            "value": {"double_value": value}
            }
        )
        self.samples[self.name].append(point)

下面的代码在 PerfMetric.samples dict 中获取一批数据点,这些数据点指向 monitoring_v3.Point class 的数组,它通过装饰器附加在方法 append 中此处未显示使用 MetricServiceClient class 调用名为 create_time_series 的 RPC。我们指向一个数组数组,所以也许这是不对的,或者我们的元数据在追加时不正确?

 @staticmethod
 def flush():
     client = monitoring_v3.MetricServiceClient()
     for x in PerfMetric.samples:
         print('{} has {} points'.format(x, len(PerfMetric.samples[x])))
         series = monitoring_v3.TimeSeries()
         series.metric.type = 'custom.googleapis.com/perf/{}'.format(x)
         series.resource.type = "global"
         series.points = PerfMetric.samples[x]
         client.create_time_series(request={
             "name": PerfMetric.project_name,
             "time_series": [series]}
         )

提前感谢您的任何建议!

我认为这是来自云监控 API 的 TimeSeries 调用中关于 points[] 数据点对象的记录限制:

When creating a time series, this field must contain exactly one point and the point's type must be the same as the value type of the associated metric.