3.16.0 (latest) 3.15.0 3.13.0 3.12.1 3.11.3 3.10.0 3.9.0 3.8.0 3.7.0 3.6.0 3.5.0 3.4.0 3.3.1 3.2.5 3.1.2 3.0.0 2.7.2 2.6.0 2.5.0 2.4.0 2.3.1 2.2.0 2.1.1 2.0.2 1.15.3 1.14.0 1.13.0 1.12.1

# Integration with logging Standard Library

We recommend that you use `google-cloud-logging` to integrate with
the Python [`logging`](https://docs.python.org/3/library/logging.html#module-logging) standard library. This way, you can write logs using Python
standards, and still have your logs appear in Google Cloud Logging.

## Automatic Configuration

To integrate `google-cloud-logging` with the standard [`logging`](https://docs.python.org/3/library/logging.html#module-logging) module,
call [`setup_logging()`](https://docs.cloud.google.com/python/docs/reference/logging/latest/client#google.cloud.logging_v2.client.Client.setup_logging) on a [`Client`](https://docs.cloud.google.com/python/docs/reference/logging/latest/client#google.cloud.logging_v2.client.Client) instance.

    # Imports the Cloud Logging client library
    import google.cloud.logging

    # Instantiates a client
    client = google.cloud.logging.https://docs.cloud.google.com/python/docs/reference/logging/latest/google.cloud.logging_v2.client.Client.html()

    # 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 higher
    client.https://docs.cloud.google.com/python/docs/reference/logging/latest/google.cloud.logging_v2.client.Client.html#google_cloud_logging_v2_client_Client_setup_logging()

You can also set the logging level threshold of the logging handler created by [`setup_logging()`](https://docs.cloud.google.com/python/docs/reference/logging/latest/client#google.cloud.logging_v2.client.Client.setup_logging),
as well as set loggers excluded from the logger that is created:

    client.setup_logging(log_level=logging.INFO)

    client.setup_logging(log_level=logging.INFO, excluded_loggers=("werkzeug",))

This [`setup_logging()`](https://docs.cloud.google.com/python/docs/reference/logging/latest/client#google.cloud.logging_v2.client.Client.setup_logging) function chooses the best configurations for the environment your
code is running on. For more information, see the [Google Cloud Logging documentation](https://cloud.google.com/logging/docs/setup/python).

## 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 in
as an argument to `setup_logging()`:

    from google.cloud.logging.handlers import CloudLoggingHandler
    from google.cloud.logging_v2.handlers import setup_logging

    handler = CloudLoggingHandler(client)
    setup_logging(handler)

There are two supported handler classes to choose from:

- [`CloudLoggingHandler`](https://docs.cloud.google.com/python/docs/reference/logging/latest/handlers-cloud-logging#google.cloud.logging_v2.handlers.handlers.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`](https://docs.cloud.google.com/python/docs/reference/logging/latest/handlers-structured-log#google.cloud.logging_v2.handlers.structured_log.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

Handler classes can also be specified via [dictConfig](https://docs.python.org/3/library/logging.config.html#logging-config-dictschema):

    import logging.config

    import google.cloud.logging

    client = google.cloud.logging.https://docs.cloud.google.com/python/docs/reference/logging/latest/google.cloud.logging_v2.client.Client.html()

    LOGGING = {
        "version": 1,
        "handlers": {
            "cloud_logging_handler": {
                "class": "google.cloud.logging.handlers.CloudLoggingHandler",
                "client": client,
            },
            "structured_log_handler": {
                "class": "google.cloud.logging.handlers.StructuredLogHandler"
            },
        },
        "root": {"handlers": [], "level": "WARNING"},
        "loggers": {
            "cloud_logger": {"handlers": ["cloud_logging_handler"], "level": "INFO"},
            "structured_logger": {
                "handlers": ["structured_log_handler"],
                "level": "INFO",
            },
        },
    }

    logging.config.dictConfig(LOGGING)

Note that since [`CloudLoggingHandler`](https://docs.cloud.google.com/python/docs/reference/logging/latest/handlers-cloud-logging#google.cloud.logging_v2.handlers.handlers.CloudLoggingHandler) requires an already initialized [`Client`](https://docs.cloud.google.com/python/docs/reference/logging/latest/client#google.cloud.logging_v2.client.Client),
you must initialize a client and include it in the dictConfig entry for a CloudLoggingHandler.

## Standard Library

After you setup the Google Cloud Logging library with the Python [`logging`](https://docs.python.org/3/library/logging.html#module-logging) standard library,
you can send logs with the standard logging library as you normally would:

    # Imports Python standard library logging
    import logging

    # The data to log
    text = "Hello, world!"

    # Emits the data using the standard logging module
    logging.warning(text)

For more information on using the Python [`logging`](https://docs.python.org/3/library/logging.html#module-logging) standard library, see the [logging documentation](https://docs.python.org/3/howto/logging.html#a-simple-example)

## Logging JSON Payloads

Although the Python [`logging`](https://docs.python.org/3/library/logging.html#module-logging) standard library [expects all logs to be strings](https://docs.python.org/3/library/logging.html#logging.Logger.debug),
Google Cloud Logging allows [JSON payload data](https://cloud.google.com/logging/docs/structured-logging).

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

1. Use the json_fields extra argument:

    import logging

    data_dict = {"hello": "world"}
    logging.info("message field", extra={"json_fields": data_dict})

1. Log a JSON-parsable string:

    import logging
    import json

    data_dict = {"hello": "world"}
    logging.info(json.dumps(data_dict))

## Automatic Metadata Detection

The Google Cloud Logging library attempts to detect and attach additional
[LogEntry fields](https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry) .
The following fields are currently supported:

- labels

- trace

- span_id

- trace_sampled

- http_request

- source_location

- resource

- json_fields

**NOTE** : More information about trace, span_id, and trace_sampled can be found [here](https://docs.cloud.google.com/python/docs/reference/logging/latest/auto-trace-span-extraction).http_request requires a [supported Python web framework](https://docs.cloud.google.com/python/docs/reference/logging/latest/web-framework-integration).## Manual Metadata Using the extra Argument

The Python [`logging`](https://docs.python.org/3/library/logging.html#module-logging) standard library accepts [an "extra" argument](https://docs.python.org/3/library/logging.html#logging.Logger.debug) when
writing logs. You can use this argument to populate LogRecord objects with user-defined
key-value pairs. Google Cloud Logging uses the extra field as a way to pass in additional
metadata to populate [LogEntry fields](https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry).

    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 the [LogEntry fields](https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry)
that can be autodetected can also be set manually through the extra argument. Fields sent explicitly through the extra
argument override any automatically detected fields.

## CloudLoggingHandler Transports

[Transport](https://docs.cloud.google.com/python/docs/reference/logging/latest/transport) classes define how the [`CloudLoggingHandler`](https://docs.cloud.google.com/python/docs/reference/logging/latest/handlers-cloud-logging#google.cloud.logging_v2.handlers.handlers.CloudLoggingHandler)
transports logs over the network to Google Cloud. There are two Transport implementations
(defined as subclasses of [`transports.base.Transport`](https://docs.cloud.google.com/python/docs/reference/logging/latest/transport#google.cloud.logging_v2.handlers.transports.base.Transport)):

- [`BackgroundThreadTransport`](https://docs.cloud.google.com/python/docs/reference/logging/latest/transport#google.cloud.logging_v2.handlers.transports.background_thread.BackgroundThreadTransport):

        * sends logs in batches, using a background thread


        * the default Transport class

- [`SyncTransport`](https://docs.cloud.google.com/python/docs/reference/logging/latest/transport#google.cloud.logging_v2.handlers.transports.sync.SyncTransport):

        * sends each log synchronously in a single API call

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

You can use both transport options over [gRPC or HTTP](https://docs.cloud.google.com/python/docs/reference/logging/latest/grpc-vs-http).

**NOTE** : [`StructuredLogHandler`](https://docs.cloud.google.com/python/docs/reference/logging/latest/handlers-structured-log#google.cloud.logging_v2.handlers.structured_log.StructuredLogHandler)
prints logs as formatted JSON to standard output, and does not use a Transport class.