@@ -62,12 +62,15 @@ class StructuredLogHandler(logging.StreamHandler):
6262 and write them to standard output
6363 """
6464
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+ ):
6668 """
6769 Args:
6870 labels (Optional[dict]): Additional labels to attach to logs.
6971 stream (Optional[IO]): Stream to be used by the handler.
7072 project (Optional[str]): Project Id associated with the logs.
73+ json_encoder_cls (Optional[Type[JSONEncoder]]): Custom JSON encoder. Defaults to json.JSONEncoder
7174 """
7275 super (StructuredLogHandler , self ).__init__ (stream = stream )
7376 self .project_id = project_id
@@ -79,6 +82,8 @@ def __init__(self, *, labels=None, stream=None, project_id=None):
7982 # make logs appear in GCP structured logging format
8083 self ._gcp_formatter = logging .Formatter (GCP_FORMAT )
8184
85+ self ._json_encoder_cls = json_encoder_cls or json .JSONEncoder
86+
8287 def format (self , record ):
8388 """Format the message into structured log JSON.
8489 Args:
@@ -95,14 +100,18 @@ def format(self, record):
95100 if key in GCP_STRUCTURED_LOGGING_FIELDS :
96101 del message [key ]
97102 # 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+ )
99106 # all json.dumps strings should start and end with parentheses
100107 # strip them out to embed these fields in the larger JSON payload
101108 if len (encoded_msg ) > 2 :
102109 payload = encoded_msg [1 :- 1 ] + ","
103110 elif message :
104111 # 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+ )
106115 payload = '"message": {},' .format (encoded_message )
107116
108117 record ._payload_str = payload or ""
0 commit comments