1616
1717import logging
1818
19+ from gcloud .logging .handlers .transports import BackgroundThreadTransport
20+
1921EXCLUDE_LOGGER_DEFAULTS = (
2022 'gcloud' ,
21- 'oauth2client.client '
23+ 'oauth2client'
2224)
2325
26+ DEFAULT_LOGGER_NAME = "python"
27+
2428
2529class CloudLoggingHandler (logging .StreamHandler , object ):
2630 """Python standard logging handler to log messages to the Google Cloud
@@ -36,6 +40,17 @@ class CloudLoggingHandler(logging.StreamHandler, object):
3640 :type client: :class:`gcloud.logging.client`
3741 :param client: the authenticated gcloud logging client for this handler
3842 to use
43+ :type name: str
44+ :param name: the name of the custom log in Stackdriver Logging. Defaults
45+ to "python". The name of the Python logger will be represented
46+ in the "python_logger" field.
47+
48+ :type transport: :class:`gcloud.logging.handlers.transports.Transport`
49+ :param transport: the class object to instantiate. It should extend from
50+ the base Transport type and implement
51+ :meth`gcloud.logging.handlers.transports.base.Transport.send`
52+ Defaults to BackgroundThreadTransport. The other
53+ option is SyncTransport.
3954
4055 Example:
4156
@@ -55,9 +70,13 @@ class CloudLoggingHandler(logging.StreamHandler, object):
5570
5671 """
5772
58- def __init__ (self , client ):
73+ def __init__ (self , client ,
74+ name = DEFAULT_LOGGER_NAME ,
75+ transport = BackgroundThreadTransport ):
5976 super (CloudLoggingHandler , self ).__init__ ()
77+ self .name = name
6078 self .client = client
79+ self .transport = transport (client , name )
6180
6281 def emit (self , record ):
6382 """
@@ -66,13 +85,11 @@ def emit(self, record):
6685 See: https://docs.python.org/2/library/logging.html#handler-objects
6786 """
6887 message = super (CloudLoggingHandler , self ).format (record )
69- logger = self .client .logger (record .name )
70- logger .log_struct ({"message" : message },
71- severity = record .levelname )
88+ self .transport .send (record , message )
7289
7390
7491def setup_logging (handler , excluded_loggers = EXCLUDE_LOGGER_DEFAULTS ):
75- """Helper function to attach the CloudLoggingAPI handler to the Python
92+ """Helper function to attach the CloudLogging handler to the Python
7693 root logger, while excluding loggers this library itself uses to avoid
7794 infinite recursion
7895
@@ -90,11 +107,11 @@ def setup_logging(handler, excluded_loggers=EXCLUDE_LOGGER_DEFAULTS):
90107
91108 import logging
92109 import gcloud.logging
93- from gcloud.logging.handlers import CloudLoggingAPIHandler
110+ from gcloud.logging.handlers import CloudLoggingHandler
94111
95112 client = gcloud.logging.Client()
96113 handler = CloudLoggingHandler(client)
97- setup_logging(handler)
114+ gcloud.logging. setup_logging(handler)
98115 logging.getLogger().setLevel(logging.DEBUG)
99116
100117 logging.error("bad news") # API call
0 commit comments