Python Logging Module Handler#

Python logging handlers for Google Cloud Logging.

class google.cloud.logging.handlers.handlers.CloudLoggingHandler(client, name='python', transport=<class 'google.cloud.logging.handlers.transports.background_thread.BackgroundThreadTransport'>)[source]#

Bases: logging.StreamHandler

Python standard logging handler.

This handler can be used to route Python standard logging messages directly to the Google Cloud Logging API.

Note that this handler currently only supports a synchronous API call, which means each logging statement that uses this handler will require an API call.

Parameters:
  • client (google.cloud.logging.client) – the authenticated Google Cloud Logging client for this handler to use
  • name (str) – the name of the custom log in Stackdriver Logging. Defaults to ‘python’. The name of the Python logger will be represented in the python_logger field.
  • transport (type) – Class for creating new transport objects. It should extend from the base Transport type and implement :meth`.Transport.send`. Defaults to BackgroundThreadTransport. The other option is SyncTransport.

Example:

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

client = google.cloud.logging.Client()
handler = CloudLoggingHandler(client)

cloud_logger = logging.getLogger('cloudLogger')
cloud_logger.setLevel(logging.INFO)
cloud_logger.addHandler(handler)

cloud.logger.error('bad news')  # API call
emit(record)[source]#

Actually log the specified logging record.

Overrides the default emit behavior of StreamHandler.

See: https://docs.python.org/2/library/logging.html#handler-objects

Parameters:record (logging.LogRecord) – The record to be logged.
google.cloud.logging.handlers.handlers.setup_logging(handler, excluded_loggers=('google.cloud', 'oauth2client'))[source]#

Attach the CloudLogging handler to the Python root logger

Excludes loggers that this library itself uses to avoid infinite recursion.

Parameters:
  • handler (logging.handler) – the handler to attach to the global handler
  • excluded_loggers (tuple) – The loggers to not attach the handler to. This will always include the loggers in the path of the logging client itself.

Example:

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

client = google.cloud.logging.Client()
handler = CloudLoggingHandler(client)
google.cloud.logging.setup_logging(handler)
logging.getLogger().setLevel(logging.DEBUG)

logging.error('bad news')  # API call