【问题标题】:How to get execution ID for Google Cloud Functions triggered from HTTP?如何获取从 HTTP 触发的 Google Cloud Functions 的执行 ID?
【发布时间】:2021-05-25 08:02:37
【问题描述】:

我正在尝试使用 Cloud Logging API 云客户端库将日志从 Python 应用程序写入 Logging,其“执行 ID”与谷歌的默认值相同。

记录器设置:

from google.cloud import logging
from google.cloud.logging.resource import Resource


log_client = logging.Client()

# This is the resource type of the log
log_name = 'cloudfunctions.googleapis.com%2Fcloud-functions'

# Inside the resource, nest the required labels specific to the resource type
res = Resource(type="cloud_function",
               labels={
                   "function_name": "my-function",
                   "region": "asia-east2"
               })
logger = log_client.logger(log_name.format("my-project"))

写日志:

logger.log_struct({"message": request.remote_addr}, resource=res, severity='INFO')

【问题讨论】:

    标签: python-3.x logging google-cloud-functions


    【解决方案1】:

    目前无法使用纯粹的 Cloud Function Framework 本身来执行此操作,但您可以尝试使用以下方法从请求本身中提取 executionId

    request.headers.get('function-execution-id')
    

    我在 Cloud Functions Github 中发现了一个问题,它跟踪获取这些值的本机方式的实现,如果您愿意,可以关注 this thread 以获取更新。

    【讨论】:

      【解决方案2】:

      我在使用旧版本的 google-cloud-logging 时遇到了同样的问题。我能够使用default python logging module 获得此功能。在运行 python 3.8 和 google-cloud-logging==2.5.0 的云函数中,executionId 与日志一起正确记录,以及堆栈驱动程序中的严重性。

      main.py:

      # Imports the Cloud Logging client library
      import google.cloud.logging
      # Instantiates a client
      client = google.cloud.logging.Client()
      
      # Retrieves a Cloud Logging handler based on the environment
      # you're running in and integrates the handler with the
      # Python logging module. By default this captures all logs
      # at INFO level and higher
      client.get_default_handler()
      client.setup_logging()
      
      
      # Imports Python standard library logging
      import logging
      def hello_world(req):
        # Emits the data using the standard logging module
        logging.info('info')
        logging.warning('warn')
        logging.error('error')
        return ""
      

      requirements.txt:

      google-cloud-logging==2.5.0
      

      触发此云函数会在 stackdriver 中产生以下结果:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-15
        • 2018-03-27
        • 2021-02-04
        • 2021-11-09
        • 2021-10-06
        相关资源
        最近更新 更多