0
votes

I am trying to attach a logging handler to the Python root logger in my cloud function. I am using below code :

    import logging
    import os
    import google.cloud.logging
    from google.cloud.logging.handlers import CloudLoggingHandler, setup_logging
    
    logLabels = {'ServerName' : os.uname().nodename}
    logging_client = google.cloud.logging.Client()
    handler = CloudLoggingHandler(logging_client,name='my-test-cf',labels=logLabels)
    logging.getLogger().setLevel(logging.INFO)
    setup_logging(handler, excluded_loggers=('google.cloud', 'google.auth', 'google_auth_httplib2'))
    logging.info(f"Starting Execution of My Test CF")

Result is duplicate log entries one with info and other with error

  1. info -> Starting Execution of My Test CF
  2. error -> Starting Execution of My Test CF

Any suggestions would be of great help. Thank you. enter image description here

1

1 Answers

1
votes

First you need to setup the logging to sent all log intries to Cloud Logging by attaching the Cloud Logging handler to the Python Root logger.

import google.cloud.logging
client = google.cloud.logging.Client()
client.get_default_handler()
client.setup_logging()

Once the handler is attached, any logs (by default INFO) which are emitted in you application will be sent to Logging.

import logging
logging.info(f"Starting Execution of My Test CF")