@@ -62,12 +62,15 @@ class StructuredLogHandler(logging.StreamHandler):
62
62
and write them to standard output
63
63
"""
64
64
65
- def __init__ (self , * , labels = None , stream = None , project_id = None ):
65
+ def __init__ (
66
+ self , * , labels = None , stream = None , project_id = None , json_encoder_cls = None
67
+ ):
66
68
"""
67
69
Args:
68
70
labels (Optional[dict]): Additional labels to attach to logs.
69
71
stream (Optional[IO]): Stream to be used by the handler.
70
72
project (Optional[str]): Project Id associated with the logs.
73
+ json_encoder_cls (Optional[Type[JSONEncoder]]): Custom JSON encoder. Defaults to json.JSONEncoder
71
74
"""
72
75
super (StructuredLogHandler , self ).__init__ (stream = stream )
73
76
self .project_id = project_id
@@ -79,6 +82,8 @@ def __init__(self, *, labels=None, stream=None, project_id=None):
79
82
# make logs appear in GCP structured logging format
80
83
self ._gcp_formatter = logging .Formatter (GCP_FORMAT )
81
84
85
+ self ._json_encoder_cls = json_encoder_cls or json .JSONEncoder
86
+
82
87
def format (self , record ):
83
88
"""Format the message into structured log JSON.
84
89
Args:
@@ -95,14 +100,18 @@ def format(self, record):
95
100
if key in GCP_STRUCTURED_LOGGING_FIELDS :
96
101
del message [key ]
97
102
# if input is a dictionary, encode it as a json string
98
- encoded_msg = json .dumps (message , ensure_ascii = False )
103
+ encoded_msg = json .dumps (
104
+ message , ensure_ascii = False , cls = self ._json_encoder_cls
105
+ )
99
106
# all json.dumps strings should start and end with parentheses
100
107
# strip them out to embed these fields in the larger JSON payload
101
108
if len (encoded_msg ) > 2 :
102
109
payload = encoded_msg [1 :- 1 ] + ","
103
110
elif message :
104
111
# properly break any formatting in string to make it json safe
105
- encoded_message = json .dumps (message , ensure_ascii = False )
112
+ encoded_message = json .dumps (
113
+ message , ensure_ascii = False , cls = self ._json_encoder_cls
114
+ )
106
115
payload = '"message": {},' .format (encoded_message )
107
116
108
117
record ._payload_str = payload or ""
0 commit comments