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.
I had tried both logging and google-cloud-logging, but they couldn't record the execution_id which is useful for debugging GCF.

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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With