16
16
17
17
import logging
18
18
19
+ from gcloud .logging .handlers .transports import BackgroundThreadTransport
20
+
19
21
EXCLUDE_LOGGER_DEFAULTS = (
20
22
'gcloud' ,
21
- 'oauth2client.client '
23
+ 'oauth2client'
22
24
)
23
25
26
+ DEFAULT_LOGGER_NAME = "python"
27
+
24
28
25
29
class CloudLoggingHandler (logging .StreamHandler , object ):
26
30
"""Python standard logging handler to log messages to the Google Cloud
@@ -36,6 +40,17 @@ class CloudLoggingHandler(logging.StreamHandler, object):
36
40
:type client: :class:`gcloud.logging.client`
37
41
:param client: the authenticated gcloud logging client for this handler
38
42
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.
39
54
40
55
Example:
41
56
@@ -55,9 +70,13 @@ class CloudLoggingHandler(logging.StreamHandler, object):
55
70
56
71
"""
57
72
58
- def __init__ (self , client ):
73
+ def __init__ (self , client ,
74
+ name = DEFAULT_LOGGER_NAME ,
75
+ transport = BackgroundThreadTransport ):
59
76
super (CloudLoggingHandler , self ).__init__ ()
77
+ self .name = name
60
78
self .client = client
79
+ self .transport = transport (client , name )
61
80
62
81
def emit (self , record ):
63
82
"""
@@ -66,13 +85,11 @@ def emit(self, record):
66
85
See: https://docs.python.org/2/library/logging.html#handler-objects
67
86
"""
68
87
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 )
72
89
73
90
74
91
def 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
76
93
root logger, while excluding loggers this library itself uses to avoid
77
94
infinite recursion
78
95
@@ -90,11 +107,11 @@ def setup_logging(handler, excluded_loggers=EXCLUDE_LOGGER_DEFAULTS):
90
107
91
108
import logging
92
109
import gcloud.logging
93
- from gcloud.logging.handlers import CloudLoggingAPIHandler
110
+ from gcloud.logging.handlers import CloudLoggingHandler
94
111
95
112
client = gcloud.logging.Client()
96
113
handler = CloudLoggingHandler(client)
97
- setup_logging(handler)
114
+ gcloud.logging. setup_logging(handler)
98
115
logging.getLogger().setLevel(logging.DEBUG)
99
116
100
117
logging.error("bad news") # API call
0 commit comments