13

I'm working on a simple Google Cloud Function that runs in the Python runtime and I want some simple logging from the Python program to Stackdriver Logging.

Based on Google's startup guide, this should be straighforward https://cloud.google.com/logging/docs/setup/python

I set up a simple test function to isolate the logging issues I'm seeing

import google.cloud.logging

def logging_test_background(data, context):

    logging_client = google.cloud.logging.Client()
    logging_client.setup_logging()

    logging.info("This should be info")
    logging.debug("This should be debug")
    logging.warning("This should be warning")
    logging.error("This should be error")

In Stackdriver Logging everything gets jumbled. enter image description here 1. Info is duplicated as an Error 2. Debug doesn't come through 3. Warning is duplicated, but both are error logging level 4. Error is duplicated

Is there something I'm missing in the configuration?

Dustin Ingram
  • 20,502
  • 7
  • 59
  • 82
ajgriese
  • 459
  • 5
  • 10

1 Answers1

10

You need to create your own logger and add the google-cloud-logging default handler to it:

import logging

from flask import Flask
from google.cloud import logging as cloudlogging

log_client = cloudlogging.Client()
log_handler = log_client.get_default_handler()
cloud_logger = logging.getLogger("cloudLogger")
cloud_logger.setLevel(logging.INFO)
cloud_logger.addHandler(log_handler)

def logging_test_background(data, context):
    cloud_logger.info("info")
    cloud_logger.warning("warn")
    cloud_logger.error("error")
    return 'OK'

Produces:

enter image description here

Dustin Ingram
  • 20,502
  • 7
  • 59
  • 82
  • 4
    I tested this code exactly. It resolves the duplicates issue and info is coming through correctly, but warning is still coming through as error. – ajgriese Jun 29 '19 at 18:41
  • Is it possible to have the `execution_id` since it's useful to trace GCF instances. – northtree Jul 03 '19 at 07:04
  • 1
    I echo what @ajgriese said. Warnings are still coming through as errors. Did you find a solution? – faridghar Jun 04 '20 at 09:33
  • 1
    What about debug? – Tjorriemorrie Jul 29 '20 at 10:29
  • @Tjorriemorrie debug-level messages didn't come through most probably because the default level is info (which is higher priority then debug) – ribitskiyb Aug 12 '20 at 19:58
  • @ajgriese Apparently this is a known issue: https://github.com/googleapis/python-logging/issues/91 They say that they don't have the resources to fix this, so we would need to wait for a while. – lopezvit Jan 18 '21 at 07:53