Integration with logging Standard Library

We recommend that you usegoogle-cloud-logging to integrate withthe Pythonlogging standard library. This way, you can write logs using Pythonstandards, and still have your logs appear in Google Cloud Logging.

Automatic Configuration

To integrategoogle-cloud-logging with the standardlogging module,callsetup_logging() on aClient instance.

# Imports the Cloud Logging client libraryimport google.cloud.logging# Instantiates a clientclient = google.cloud.logging.Client()# Retrieves a Cloud Logging handler based on the environment# you're running in and integrates the handler with the# Python logging module. By default this captures all logs# at INFO level and higherclient.setup_logging()

Thissetup_logging() function chooses the best configurations for the environment yourcode is running on. For more information, see theGoogle Cloud Logging documentation.

Manual Handler Configuration

Automatic Configuration automatically determines the appropriate handler for the environment.To specify the handler yourself, construct an instance manually and pass it inas an argument tosetup_logging():

from google.cloud.logging.handlers import CloudLoggingHandlerfrom google.cloud.logging_v2.handlers import setup_logginghandler = CloudLoggingHandler(client)setup_logging(handler)

There are two supported handler classes to choose from:

  • CloudLoggingHandler:

      * Sends logs directly to Cloud Logging over the network ([gRPC or HTTP](grpc-vs-http.md))  * Logs are transmitted according to a Transport class  * This is the default handler on most environments, including local development
  • StructuredLogHandler:

      * Outputs logs as [structured JSON](https://cloud.google.com/logging/docs/structured-logging#special-payload-fields)

    to standard out, to be read and parsed by a GCP logging agent

      * This is the default handler on Kubernetes Engine, Cloud Functions and Cloud Run

Standard Library

After you setup the Google Cloud Logging library with the Pythonlogging standard library,you can send logs with the standard logging library as you normally would:

# Imports Python standard library loggingimport logging# The data to logtext = "Hello, world!"# Emits the data using the standard logging modulelogging.warning(text)

For more information on using the Pythonlogging standard library, see thelogging documentation

Logging JSON Payloads

Although the Pythonlogging standard libraryexpects all logs to be strings,Google Cloud Logging allowsJSON payload data.

To write JSON logs using the standard library integration, do one of the following:

  1. Use the json_fields extra argument:
import loggingdata_dict = {"hello": "world"}logging.info("message field", extra={"json_fields": data_dict})
  1. Log a JSON-parsable string:
import loggingimport jsondata_dict = {"hello": "world"}logging.info(json.dumps(data_dict))

Automatic Metadata Detection

The Google Cloud Logging library attempts to detect and attach additionalLogEntry fields .The following fields are currently supported:

  • labels

  • trace*

  • span_id*

  • trace_sampled*

  • http_request*

  • source_location

  • resource

  • json_fields

NOTE: Fields marked with “*” require a supported Python web framework. The Google Cloud Logginglibrary currently supportsflask anddjango

Manual Metadata Using the extra Argument

The Pythonlogging standard library acceptsan “extra” argument whenwriting logs. You can use this argument to populate LogRecord objects with user-definedkey-value pairs. Google Cloud Logging uses the extra field as a way to pass in additionalmetadata to populateLogEntry fields.

my_labels = {"foo": "bar"}my_http = {"requestUrl": "localhost"}my_trace = "01234"logging.info(    "hello", extra={"labels": my_labels, "http_request": my_http, "trace": my_trace})

All of theLogEntry fieldsthat can be autodetected can also be set manually through the extra argument. Fields sent explicitly through the extraargument override any automatically detected fields.

CloudLoggingHandler Transports

Transport classes define how theCloudLoggingHandlertransports logs over the network to Google Cloud. There are two Transport implementations(defined as subclasses oftransports.base.Transport):

You can set a Transport class by passing it as an argument wheninitializing CloudLoggingHandler manually.

You can use both transport options overgRPC or HTTP.

NOTE:StructuredLogHandlerprints logs as formatted JSON to standard output, and does not use a Transport class.

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-10-30 UTC.