Google Cloud Logging

3.15.0 · active · verified Sat Mar 28

The `google-cloud-logging` client library for Python allows developers to interact with the Google Cloud Logging API. It facilitates sending and retrieving log entries, managing log sinks, and integrating with Python's standard `logging` module. The library is actively maintained by Google, with version 3.15.0 being the latest, and releases frequently align with updates across the broader Google Cloud Python ecosystem.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the `google-cloud-logging` client and integrate it with Python's standard `logging` module. It also shows how to directly use the client for more granular control over log entries, including structured logging. For local development, ensure Application Default Credentials are configured, or explicitly provide a project ID.

import google.cloud.logging
import logging
import os

# For local execution, ensure Application Default Credentials are set up.
# E.g., by running `gcloud auth application-default login` or setting GOOGLE_APPLICATION_CREDENTIALS.
# For deployments on GCP (e.g., Cloud Run, GKE, Compute Engine), credentials are often automatic.

# Optional: Set the project ID explicitly if not running on GCP or if default is incorrect.
# project_id = os.environ.get('GOOGLE_CLOUD_PROJECT', 'your-gcp-project-id')
client = google.cloud.logging.Client()

# Attaches a Cloud Logging handler to the root Python logger.
# All standard Python logging calls (e.g., logging.info, logging.error)
# will now be sent to Google Cloud Logging.
# In serverless environments (Cloud Functions, Cloud Run, GKE), this often
# defaults to StructuredLogHandler, which writes JSON to stdout/stderr.
client.setup_logging(log_level=logging.INFO)

# Use Python's standard logging to send logs
logging.info('This is an info message via standard Python logging.')
logging.warning('This is a warning message with some data.', extra={'json_fields': {'user_id': '123', 'session': 'abc'}})
logging.error('An error occurred!')

# To use the Cloud Logging client directly for more control (e.g., custom log names, resources)
logger = client.logger(name='my-custom-log', labels={'source': 'quickstart'})
logger.log_text('This is a direct log entry to my-custom-log.')
logger.log_struct(
    {'message': 'Structured log entry!', 'severity': 'DEBUG', 'component': 'backend'},
    severity='DEBUG'
)

print('Logs sent to Google Cloud Logging.')

view raw JSON →