Google Cloud App Engine Logging

1.9.0 · active · verified Sat Apr 04

The `google-cloud-appengine-logging` Python client library provides an interface to Google Cloud Logging specifically tailored for applications running on Google App Engine. It enables developers to integrate Python's standard `logging` module with Cloud Logging, facilitating the collection, storage, and analysis of application logs. The current version is 1.9.0, and being part of the `google-cloud-python` monorepo, it receives frequent updates for bug fixes and feature enhancements across various Google Cloud services.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to integrate `google-cloud-appengine-logging` with Python's standard `logging` module. It initializes the Cloud Logging client and then configures it to capture logs from the root Python logger, sending them to your specified Google Cloud project. This setup is particularly useful for App Engine applications to ensure logs are visible in Cloud Logging's Logs Explorer. Remember to replace 'your-gcp-project-id' with your actual project ID, or ensure the `GOOGLE_CLOUD_PROJECT` environment variable is set.

import os
import logging
from google.cloud import logging as cloud_logging

# Set your Google Cloud Project ID
# For local testing, ensure GOOGLE_APPLICATION_CREDENTIALS is set or you're logged in via `gcloud auth application-default login`
PROJECT_ID = os.environ.get('GOOGLE_CLOUD_PROJECT', 'your-gcp-project-id')

# Instantiate a Cloud Logging client
client = cloud_logging.Client(project=PROJECT_ID)

# Connects the Cloud Logging client to the root Python logging handler
# This will capture all logs at INFO level and higher by default
client.setup_logging()

# Get a standard Python logger
logger = logging.getLogger(__name__)

# Log messages using the standard Python logging module
logger.info('This is an informational message.')
logger.warning('A warning occurred in the application.')
logger.error('An error was encountered!')

try:
    1 / 0
except ZeroDivisionError:
    logger.exception('Caught an exception!')

print(f'Logs sent to Google Cloud Logging for project: {PROJECT_ID}')

view raw JSON →