Google Cloud App Engine Logging
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
- breaking Migration from App Engine First-Generation Runtimes to Second-Generation Runtimes changes logging behavior significantly. Pre-integrated logging is not supported, and logs are no longer automatically correlated. You must explicitly use the Cloud Logging client library to achieve proper log correlation and structured logging.
- gotcha Logs from the `google`-level logger are not propagated to the root Python logger by default. This means if you expect logs from Google client libraries to appear in your general application log streams (e.g., stdout/stderr handlers attached to the root logger), you need to explicitly configure propagation.
- gotcha Logs may contain sensitive information. The library itself logs RPC events that might include sensitive data. Exercise caution when collecting, storing, and accessing logs to comply with data privacy and security policies.
- gotcha For optimal analysis in Cloud Logging's Logs Explorer, especially when wanting parsed fields, it's recommended to log structured JSON payloads instead of plain text strings. While plain text logs are ingested, they appear in a `textPayload` field without easy field-based filtering.
Install
-
pip install google-cloud-appengine-logging
Imports
- logging
from google.cloud import logging
Quickstart
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}')