From 835a7e45c7338cd56f32095a338408f4fcd53452 Mon Sep 17 00:00:00 2001 From: Aidan Feldman Date: Tue, 24 Nov 2026 01:36:48 -0500 Subject: [PATCH] docs: add Structured Logging section to README Shows how to attach google-cloud-logging's StructuredLogHandler to the Python root logger so Cloud Run/Cloud Functions log entries get correct severity levels and automatic trace correlation via X-Cloud-Trace-Context. Generated by a bot on behalf of Aidan. --- README.md | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/README.md b/README.md index d564ad92..8f4572b4 100644 --- a/README.md +++ b/README.md @@ -341,6 +341,35 @@ documentation on See the [running example](examples/cloud_run_event). +## Structured Logging + +When running in Cloud Run or Cloud Run Functions, log entries written as plain +text to stdout won't have a severity level parsed by Cloud Logging. To enable +structured logging with correct severity and automatic trace correlation, install +[`google-cloud-logging`](https://pypi.org/project/google-cloud-logging/) and +attach its `StructuredLogHandler` to the Python root logger: + +```python +import logging +import functions_framework +from google.cloud.logging_v2.handlers import StructuredLogHandler + +logging.basicConfig(handlers=[StructuredLogHandler()], level=logging.INFO) + + +@functions_framework.http +def hello(request): + logging.info("Processing request") + return "Hello world!" +``` + +`StructuredLogHandler` formats each log record as a JSON object with a +`severity` field, which Cloud Logging uses to set the entry's severity level. +When inside a request handler, it also automatically populates +`logging.googleapis.com/trace` and `spanId` from the `X-Cloud-Trace-Context` +request header so your function's log entries are correlated with the parent +request trace. + ## Advanced Examples More advanced guides can be found in the [`examples/`](examples/) directory.