I've tried using this example code from the Cloud Functions docs:
# PROJECT = 'The project ID of your Cloud Run service';
global_log_fields = {}
trace_header = request.headers.get('X-Cloud-Trace-Context')
trace = trace_header.split('/')
global_log_fields['logging.googleapis.com/trace'] = (
f"projects/{PROJECT}/traces/{trace[0]}")
entry = dict(severity='NOTICE',
message='This is the default display field.',
# Log viewer accesses 'component' as jsonPayload.component'.
component='arbitrary-property',
**global_log_fields)
print(json.dumps(entry))
In the Log Explorer, the corresponding logged items look something like:
{
textPayload: "{"severity": "NOTICE", "message": "This is the default display field.", "component": "arbitrary-property", "logging.googleapis.com/trace": "projects/[...]/traces/abaa6a6d18e3dd498347c43ad9137d0b"}"
insertId: "[...]"
resource: {[...]}
timestamp: "2020-11-20T17:39:45.613Z"
severity: "INFO"
labels: {[...]}
logName: "projects/[...]/logs/cloudfunctions.googleapis.com%2Fcloud-functions"
trace: "projects/[...]/traces/abaa6a6d18e3dd498347c43ad9137d0b"
receiveTimestamp: "2020-11-20T17:39:55.906103427Z"
}
The main issue being that the json representation is stuffed into the textPayload
field rather than showing up in jsonPayload
in structured form.
It's also interesting that the trace
value on the log item seems to be automagically set already, suggesting there's no need for me to read the 'X-Cloud-Trace-Context'
header on the request. (I confirmed that the trace value is definitely not being read from my json payload. It still appears if I remove the logging.googleapis.com/trace
field from the logged dictionary.)