Structlog Google Cloud Logging Processors

0.5.0 · active · verified Wed Apr 15

structlog-gcp is a Python library that provides a set of structlog processors designed to output logs in the Google Cloud Logging format. It is intended for applications running in Google Cloud environments like GKE or Cloud Functions, facilitating easy integration with Google Cloud Logging and Error Reporting. The library, currently at version 0.5.0, has an active development cycle with regular releases addressing bug fixes and new features.

Warnings

Install

Imports

Quickstart

Configures structlog to use the Google Cloud Logging compatible processors. Logs are printed to stdout as JSON, suitable for ingestion by Google Cloud Logging. Exceptions passed with `exception=e` are formatted for Google Error Reporting.

import structlog
import structlog_gcp
import os

# Configure structlog with GCP processors
processors = structlog_gcp.build_processors(
    service=os.environ.get('K_SERVICE', 'my-app-service'),
    version=os.environ.get('K_REVISION', 'v1.0.0')
)

structlog.configure(processors=processors)

logger = structlog.get_logger().bind(request_id='abc-123')

logger.info('User login successful', username='testuser', user_id=123)

try:
    1 / 0
except ZeroDivisionError as e:
    logger.error('An error occurred during calculation', error_type='division_by_zero', exception=e)
    logger.warning('This warning will not be reported to Error Reporting if exception object is not passed.')

# Example of binding context variables (requires 'structlog.contextvars.merge_contextvars' in processors)
# logger.bind(correlation_id='xyz-456')
# logger.info('Operation step completed')

view raw JSON →