I tried to write a function that will hide a sensitive data from logs. But I am thinking about the optimizations. For example about reduction a nested loops. There are two options how a logs can pass in the function. First is as string, the second is as object that have a __dict__ where "args" located. For exaple in a log
logger.debug(
"%s Body: '%s'",
self.id,
self.body,
)
args will contain a tuple of args: ("some id", "some body")
def _hide_sensitive_data(record):
to_hide = ["access_token", "password"]
items = record.__dict__.get("args")
record_list = list(items)
try:
for i, item in enumerate(record_list):
for field in to_hide:
if field in str(item):
try:
record_json = json.loads(item)
record_json[field] = "*****"
record_list[i] = record_json
except json.JSONDecodeError:
pattern = re.compile(r'(password=|access_token=)([^& ]+)')
record_list[i] = re.sub(pattern, r'\2*****', item)
record.__dict__["args"] = tuple(record_list)
except TypeError:
pass
Can you give an advice how to optimize this code?