读取 Storage 触发云函数的日志

Read logs of a Storage trigger cloud function

我需要读取存储触发云功能的状态,日志的最后一行

2021-03-09 15:47:42.908 IST function_name 6cymbohrrv6g Function execution took 11 ms, finished with status: 'ok'

这样我就可以确定函数执行是否成功。

我尝试使用以下脚本读取日志,但它显示了所有日志。

    logging_client = logging.Client()
    for entry in logging_client.list_entries():
         timestamp = entry.timestamp.isoformat()
         print("* {}: {}".format(timestamp, entry.payload))

有什么方法可以限制当前执行的日志吗?我可以阅读显示功能状态的最后一个日志吗?

您可以在 logging_client.list_entries() method 中使用高级过滤器。 Stackdriver Logging 的 Python 客户端库的官方文档承认此参数。

filter (str) – a filter expression. See https://cloud.google.com/logging/docs/view/advanced_filters

例如:

from google.cloud import logging

logging_client = logging.Client()
f = 'resource.type="cloud_function" AND resource.labels.function_name="yourFunctionName" AND textPayload:"Function execution took"'
for entry in logging_client.list_entries(filter_=f):
    print("{} {}".format(entry.labels['execution_id'], entry.payload))

将输出:

...
gssssmirx021 Function execution took 20522 ms, finished with status code: 200
gsssn1aibbc5 Function execution took 20022 ms, finished with status code: 200

请注意 substring operator (:) textPayload:"Function execution took"