Home > Software design >  GCP Cloud Functions printing extra blank line after every print statement
GCP Cloud Functions printing extra blank line after every print statement

Time:08-05

I have a Cloud Function running Python 3.7 runtime triggered from a Pub/Sub Topic.

In the code, I have places where I use print() to write logs. However, when I go to the logs tab of my function, I see that an extra blank line is added after each log. I would like to remove these, since this is basically doubling my usage of the Logging API.

I have tried using print(message, end="") but this did not remove the blank lines.

Thanks in advance.

enter image description here

CodePudding user response:

Instead of using print. Use Logger.

import logging
import logging.handlers as handlers

logger = logging.getLogger("YourCloudFunctionLoggerName")
logger.setLevel(logging.DEBUG)

CodePudding user response:

Although I have not found out the root cause for the blank line, I was able to resolve this by using the google-cloud-logging library as suggested by John in the comment of my question.

Resulting code is as below:

import google.cloud.logging
import logging

# set up logging client when run on GCP
if not os.environ.get("DEVELOPMENT"): # custom environment variable
    # only on GCP
    logging_client = google.cloud.logging.Client()
    logging_client.setup_logging()


# define logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG) # min logging level for logger
# define handler only on local

# only add handlers in local, since Cloud Function there already is a handler attached to the logger
# adding another handler in Cloud Function will result in duplicate logging with severity = ERROR
if os.environ.get("DEVELOPMENT"):
    console_handler = logging.StreamHandler() # handler to write to stream
    console_handler.setLevel(logging.DEBUG) # min logging level for handler
    # add handler to logger
    logger.addHandler(console_handler)

def my_function():
    logger.info('info')

This code will,

  • not send code to GCP logs when function is executed on local
  • will print INFO and DEBUG logs both on local and on GCP

Thank you both for your suggestions.

  • Related