Search code examples
python-3.xgoogle-app-enginegoogle-cloud-platformstackdrivergoogle-cloud-stackdriver

stackdriver logging client library missing severity with python


i would like to send more expressive log entries to stackdriver logging from my app engine standard python3 app. By following the official documentation i was able to send my logs to stackdriver and it seems that the timestamp is parsed correctly.

But i'm missing the severity levels. In addition i see no way to link logs for a certain request together to a operation. Something that the java logging seems to be doing out of the box.

For reference here is my code:

import logging
import os

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

app = Flask(__name__)
log_client = glog.Client(os.getenv('GOOGLE_CLOUD_PROJECT'))
# Attaches a Google Stackdriver logging handler to the root logger
log_client.setup_logging()


@app.route('/_ah/push-handlers/cloudbuild', methods=['POST'])
def pubsub_push_handle():

    logging.info("stdlib info")
    logging.warning("stdlib warn")
    logging.error("stdlib error")

logs resulting in stackdriver:

logs in stackdriver

As you can see the timestamps and message are available while the severity is strangely missing and it gets classified as 'Any'

Can someone point me in the right direction or is this level of incorporation not yet available?

Thanks for your time! Carsten


Solution

  • 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)
    
    app = Flask(__name__)
    
    @app.route('/_ah/push-handlers/cloudbuild', methods=['POST'])
    def pubsub_push_handle():
        cloud_logger.info("info")
        cloud_logger.warning("warn")
        cloud_logger.error("error")
        return 'OK'
    

    Produces:

    enter image description here