33
33
"werkzeug" ,
34
34
)
35
35
36
+ """These environments require us to remove extra handlers on setup"""
36
37
_CLEAR_HANDLER_RESOURCE_TYPES = ("gae_app" , "cloud_function" )
37
38
39
+ """Extra trace label to be added on App Engine environments"""
40
+ _GAE_TRACE_ID_LABEL = "appengine.googleapis.com/trace_id"
41
+
42
+ """Resource name for App Engine environments"""
43
+ _GAE_RESOURCE_TYPE = "gae_app"
44
+
38
45
39
46
class CloudLoggingFilter (logging .Filter ):
40
47
"""Python standard ``logging`` Filter class to add Cloud Logging
@@ -45,10 +52,6 @@ class CloudLoggingFilter(logging.Filter):
45
52
overwritten using the `extras` argument when writing logs.
46
53
"""
47
54
48
- # The subset of http_request fields have been tested to work consistently across GCP environments
49
- # https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#httprequest
50
- _supported_http_fields = ("requestMethod" , "requestUrl" , "userAgent" , "protocol" )
51
-
52
55
def __init__ (self , project = None , default_labels = None ):
53
56
self .project = project
54
57
self .default_labels = default_labels if default_labels else {}
@@ -80,13 +83,6 @@ def filter(self, record):
80
83
user_labels = getattr (record , "labels" , {})
81
84
# infer request data from the environment
82
85
inferred_http , inferred_trace , inferred_span = get_request_data ()
83
- if inferred_http is not None :
84
- # filter inferred_http to include only well-supported fields
85
- inferred_http = {
86
- k : v
87
- for (k , v ) in inferred_http .items ()
88
- if k in self ._supported_http_fields and v is not None
89
- }
90
86
if inferred_trace is not None and self .project is not None :
91
87
# add full path for detected trace
92
88
inferred_trace = f"projects/{ self .project } /traces/{ inferred_trace } "
@@ -188,12 +184,17 @@ def emit(self, record):
188
184
record (logging.LogRecord): The record to be logged.
189
185
"""
190
186
message = super (CloudLoggingHandler , self ).format (record )
187
+ labels = record ._labels
188
+ resource = record ._resource or self .resource
189
+ if resource .type == _GAE_RESOURCE_TYPE and record ._trace is not None :
190
+ # add GAE-specific label
191
+ labels = {_GAE_TRACE_ID_LABEL : record ._trace , ** (labels or {})}
191
192
# send off request
192
193
self .transport .send (
193
194
record ,
194
195
message ,
195
- resource = ( record . _resource or self . resource ) ,
196
- labels = record . _labels ,
196
+ resource = resource ,
197
+ labels = labels ,
197
198
trace = record ._trace ,
198
199
span_id = record ._span_id ,
199
200
http_request = record ._http_request ,
0 commit comments