I am working on some code where half the code seems to be logging and timing various things. I find this clutters up the real code. I was wondering what are the approaches to still logging everything but cleanly separating the logging and real code?
e.g. some block of code could do something as simple as:
for item in files: parsed_item = parse_item(item)
but to log it could produce a lot more code which clutters up the real code e.g.
folders = 0 files = 0 paid_users = 0 free_users = 0 for item in files: parsed_item = parse_item(item) if parsed_item['isFolder']: folders += 1 else: files += 1 if parsed_item['isPaidUser']: paid_users += 1 else: free_users += 1 logger.info('Parsed: %d folders %d files %d paid users %d free users' % folders, files, paid_users, free_users)
Potentially there could be something cleaner where we use a decorator or context manager for the block of code and then do some logging on the
__exit__() method e.g.
with parse_files_logger() as logger: for item in files: parsed_item = parse_item(item) logger.log(parsed_item)
but keen to see if there are cleaner alternatives?