Python log_struct output appears as JSON {"message":"Log struct"} in the logs viewer?

250 views
Skip to first unread message

John Carter

unread,
Jul 30, 2019, 12:46:36 AM7/30/19
to Google Stackdriver Discussion Forum
I'm trying to get structured logging working from a Python 3.7 Google Cloud Function, using google-cloud-logging log_struct, while still retaining the useful information attached to print() logs like display of function_name, execution_id etc.

I've nearly got it working, but I'm finding that if I use the logger name "cloudfunctions.googleapis.com%2Fcloud-functions" as per the default logs then my message appears in the Stackdriver logs viewer web page as a JSON dict instead of just showing the message.
If use a different logger name then message is shown correctly, but then the function name and execution id aren't shown in the log view by default.

Is there a way to configure it so both are shown?

I can fake the result I want by using a different log name and editing the custom fields in the Stackdriver logs viewer, but that's annoying to have to do, and seems redundant.


google_cloud_function_stackdriver.png





Cloud function that produced the above:


def hello_world(request: "flask.Request"):
from google.cloud import logging as cloud_logging
from google.cloud.logging.resource import Resource
client = cloud_logging.Client()

print("Example print")

for logger_name in ("cloudfunctions.googleapis.com%2Fcloud-functions", "my-logs"):
# Setting logger name = "cloudfunctions.googleapis.com%2Fcloud-functions" seems to
# causes the log struct to show as a JSON string instead of showing the message?

google_logger = client.logger(logger_name)

# see https://stackoverflow.com/questions/54660919/how-to-logging-with-different-severity-levels-in-google-cloud-functions/54673381#54673381
execution_id = request.headers.get("Function-Execution-Id")
function_name = os.environ.get("FUNCTION_NAME")
function_region = os.environ.get("FUNCTION_REGION")
project_name = os.environ.get("X_GOOGLE_GCLOUD_PROJECT")
trace, sep, end = request.headers.get("X-Cloud-Trace-Context", "").partition("/")
if trace:
trace = f"projects/{project_name}/traces/{trace}"

google_logger.log_struct(
{"message": "Log struct"},
labels={"execution_id": execution_id},
resource=Resource(type="cloud_function", labels={"function_name": function_name, "region": function_region}),
severity="WARNING",
trace=trace
)

return "done"
Reply all
Reply to author
Forward
0 new messages