4

I had deployed Cloud Functions with runtime python37. My question is how to print or logging with different severity and same execution_id, which could be easy to filter by log level via Stackdriver Logging interface.

By default, print will use the same execution_id, but I couldn't specify the severity.enter image description here

I had tried both logging and google-cloud-logging, but they couldn't record the execution_id which is useful for debugging GCF. enter image description here

northtree
  • 8,569
  • 11
  • 61
  • 80

2 Answers2

7

If you really want execution id that print would take by default, it's available in request.headers.get("Function-Execution-Id") for https triggered function and for background function, it is same as context.event_id. So you can modify llompalles's answer and create Resource inside the function and add execution id to the resource

Raghava Dhanya
  • 959
  • 15
  • 22
3

Currently there is no way to add the execution_id to the logs entries. But following the approach in this answer you can easily filter the logs entries belonging to the same function execution in the Stackdriver Logging interface.

With this Cloud Function code:

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) 

Once executed open the log entry in the Strackdriver Logging interface. Display the jsonPayload and clicking in the id element it will display Show matching entries. This will add the filter:

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

And all the logs entry belonging to this execution will be shown.

Finally, just keep in mind that Cloud Function Python 3.7 runtime is still in beta and might be subject to future changes.

llompalles
  • 3,072
  • 11
  • 20
  • Should the global `identifier` be initialised once or multiple times for each call? – northtree Feb 14 '19 at 01:14
  • The identifier will be initialized once every time the Cloud Function is called. So it will act as a sort of `execution_id`. – llompalles Feb 14 '19 at 08:21
  • `execution_id` should change on every call, but your `identifier` will only change when the function environment is restarted – John Carter Jul 30 '19 at 02:03