从 Google Cloud 中的警报策略触发云功能

问题描述 投票:0回答:1

我创建了一个执行数据库查询并返回计数的 Google Cloud 函数:

import psycopg2

def my_function(request):
  """Runs a custom SQL query on a Cloud SQL database and returns the result."""

  # Connect to the Cloud SQL database.
  conn = psycopg2.connect(host='<YOUR_DATABASE_HOST>', database='<YOUR_DATABASE_NAME>', user='<YOUR_DATABASE_USER>', password='<YOUR_DATABASE_PASSWORD>')

  # Create a cursor.
  cur = conn.cursor()

  # Run the custom SQL query.
  cur.execute('SELECT count(*) FROM <YOUR_TABLE_NAME> WHERE <YOUR_FIELD> IS NULL OR LTRIM(RTRIM(<YOUR_FIELD>)) = ''')

  # Fetch the result of the query.
  result = cur.fetchone()[0]

  # Close the cursor and connection.
  cur.close()
  conn.close()

  # Return the result of the query.
  return result

测试成功,返回正确值。我现在正在尝试创建一个警报策略,每小时触发此函数并检查返回的数量是否增加或保持不变,但我似乎找不到方法来做到这一点。

我尝试使用此 MQL 代码,但它不起作用:

sum(resource.labels.function_name = "<YOUR_FUNCTION_NAME>")

google-cloud-platform alert
1个回答
0
投票

云监控仅根据日志进行分析。因此,它无法调用函数来获取值。

因此,正确的选择如下

  • 更新您的云函数以将结果写入日志中(并返回“hello world”而不是结果)
  • 创建一个每小时调用您的函数的云调度程序
  • 根据您使用 Cloud Functions 写入的日志,在 Cloud Logging 中创建基于日志的指标
  • 针对指标创建
  • 警报策略
© www.soinside.com 2019 - 2024. All rights reserved.