【问题标题】:How to logging with different severity levels in Google Cloud Functions如何在 Google Cloud Functions 中使用不同的严重级别进行日志记录
【发布时间】:2019-07-06 17:44:55
【问题描述】:

我已经使用运行时 python37 部署了 Cloud Functions。我的问题是如何使用不同的severity 和相同的execution_id 打印或记录日志,这可以通过Stackdriver Logging 界面轻松按日志级别过滤。

默认情况下,print 将使用相同的 execution_id,但我无法指定 severity.

logginggoogle-cloud-logging 我都试过了,但他们无法记录对调试 GCF 有用的execution_id

【问题讨论】:

    标签: python logging google-cloud-functions stackdriver google-cloud-logging


    【解决方案1】:

    如果您真的想要print 默认采用的执行ID,它在request.headers.get("Function-Execution-Id") 中可用于https 触发函数和后台函数,它与context.event_id 相同。所以你可以修改llompalles's answer并在函数内部创建Resource,并将执行id添加到资源中

    【讨论】:

      【解决方案2】:

      目前无法将execution_id 添加到日志条目中。但是按照this answer中的方法,您可以在Stackdriver Logging界面中轻松过滤属于同一功能执行的日志条目。

      使用此云功能代码:

      import time
      from google.cloud import logging
      from google.cloud.logging.resource import Resource
      
      identifier = str(time.time())
      
      log_client = logging.Client()
      
      log_name = 'cloudfunctions.googleapis.com%2Fcloud-functions' 
      resource = Resource(type="cloud_function", labels={"function_name": "yourCloudFunctionName", "region": "yourFunctionLocation"})
      logger   = log_client.logger(log_name.format("yourProjectId"))
      
      def hello_world(request):
      
          logger.log_struct({"message": "message string to log", "id": identifier}, resource=resource, severity='ERROR')
      
          return 'Wrote logs to {}.'.format(logger.name) 
      

      执行后,在 Strackdriver Logging 界面中打开日志条目。显示jsonPayload 并单击id 元素,它将显示Show matching entries。这将添加过滤器:

      resource.type="cloud_function"
      resource.labels.function_name="yourFunctionName"
      jsonPayload.id="theID"
      

      并且将显示属于此执行的所有日志条目。

      最后,请记住,Cloud Function Python 3.7 运行时仍处于测试阶段,未来可能会发生变化。

      【讨论】:

      • 全局identifier应该为每次调用初始化一次还是多次?
      • 每次调用Cloud Function都会初始化一次标识符。所以它将充当一种execution_id
      • execution_id 应该在每次调用时改变,但你的identifier 只会在函数环境重新启动时改变
      猜你喜欢
      • 1970-01-01
      • 2014-12-27
      • 2019-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-08
      • 1970-01-01
      相关资源
      最近更新 更多