Google Cloud Functions Logging (Python)

June 5, 2019

TLDR

Use standard Python logging

import logging

logger = logging.getLogger(__name__)

def test_logging(request):
    logger.info("I am logger")
    logging.info("I am logging")
    return 'OK'

Testing logging

Testing

  • logging
  • logging.getLogger
  • google.cloud.logging
  • integrate google.cloud.logging with logging.getLogger

Edit requirements.txt

# https://pypi.org/project/google-cloud-logging/
google-cloud-logging==1.11.0

Testing Code

import logging

logger = logging.getLogger(__name__)

# https://cloud.google.com/logging/docs/reference/libraries#client-libraries-install-python
from google.cloud import logging as glogging
# client = glogging.Client.from_service_account_json('keys/PROJECT_ID-appengine.json')
client = glogging.Client()
cloud_log = client.logger(__name__)

# https://googleapis.github.io/google-cloud-python/latest/logging/usage.html#integration-with-python-logging-module
handler = client.get_default_handler()
cloud_logger = logging.getLogger("cloudLogger")
# cloud_logger.setLevel(logging.INFO)
cloud_logger.addHandler(handler)

def test_logging(request):
    logger.info("--- START ---")

    logger.debug("logger.debug")
    logger.info("logger.info")
    logger.warn("logger.warn")
    logger.error("logger.error")

    logger.info("---")

    logging.debug("logging.debug")
    logging.info("logging.info")
    logging.warn("logging.warn")
    logging.error("logging.error")

    logger.info("---")

    # https://cloud.google.com/logging/docs/api/tasks/creating-logs
    # https://cloud.google.com/service-infrastructure/docs/service-control/reference/rpc/google.logging.type#logseverity
    cloud_log.log_text("cloud_logging.debug", severity='DEBUG')
    cloud_log.log_text("cloud_logging.info", severity='INFO')
    cloud_log.log_text("cloud_logging.warn", severity='WARNING')
    cloud_log.log_text("cloud_logging.error", severity='ERROR')

    logger.info("---")

    cloud_logger.debug("cloud_logger.debug")
    cloud_logger.info("cloud_logger.info")
    cloud_logger.warn("cloud_logger.warn")
    cloud_logger.error("cloud_logger.error")

    logger.info("--- END ---")
    return 'OK'

Output

Google Cloud Functions Logging

Conclusion

logging.getLogger and logging works

  • Strangely, .warn and .error are both mark as Error severity
  • .debug is filtered by default, I assume it could be changed by .setLevel(logging.DEBUG) (I didn’t test this though)

Strangely, google.cloud.logging - log_text didn’t work, and I didn’t explore further. You might want to try this.

Integrating google.cloud.logging with logging.getLogger works the same as logging.getLogger and logging.

References:

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.