5050from opentelemetry .sdk ._logs .export import LogExporter
5151from opentelemetry .sdk .resources import Resource
5252from opentelemetry .trace import format_span_id , format_trace_id
53+ from opentelemetry .util .types import AnyValue
5354
5455DEFAULT_MAX_ENTRY_SIZE = 256000 # 256 KB
5556DEFAULT_MAX_REQUEST_SIZE = 10000000 # 10 MB
@@ -117,19 +118,28 @@ def _convert_any_value_to_string(value: Any) -> str:
117118 return ""
118119
119120
120- def _convert_bytes_to_b64 (body : Mapping , new_body : dict ) -> dict :
121+ # Be careful not to mutate original body. Make copies of anything that needs to change.
122+ def _sanitized_body (
123+ body : Mapping [str , AnyValue ]
124+ ) -> MutableMapping [str , AnyValue ]:
125+ new_body : MutableMapping [str , AnyValue ] = {}
121126 for key , value in body .items ():
122127 if (
123128 isinstance (value , Sequence )
124129 and len (value ) > 0
125130 and isinstance (value [0 ], bytes )
126131 ):
127- new_body [key ] = [base64 .b64encode (v ).decode () for v in value ]
132+ # Should not be possible for a non-bytes value to be present. AnyValue requires Sequence be of one type, and above
133+ # we verified the first value is type bytes.
134+ new_body [key ] = [
135+ base64 .b64encode (v ).decode ()
136+ for v in value
137+ if isinstance (v , bytes )
138+ ]
128139 elif isinstance (value , bytes ):
129140 new_body [key ] = base64 .b64encode (value ).decode ()
130- elif isinstance (value , MutableMapping ):
131- new_subbody = {}
132- new_body [key ] = _convert_bytes_to_b64 (value , new_subbody )
141+ elif isinstance (value , Mapping ):
142+ new_body [key ] = _sanitized_body (value )
133143 else :
134144 new_body [key ] = value
135145 return new_body
@@ -138,8 +148,7 @@ def _convert_bytes_to_b64(body: Mapping, new_body: dict) -> dict:
138148def _set_payload_in_log_entry (log_entry : LogEntry , body : AnyValue ):
139149 struct = Struct ()
140150 if isinstance (body , Mapping ):
141- new_body = {}
142- struct .update (_convert_bytes_to_b64 (body , new_body ))
151+ struct .update (_sanitized_body (body ))
143152 log_entry .json_payload = struct
144153 elif isinstance (body , bytes ):
145154 json_str = body .decode ("utf-8" , errors = "replace" )
0 commit comments