I'm trying to use the logging library in Python to write lists of strings to a CSV log file
Logger creation:
export_logger = logging.getLogger('exportLogger')
export_logger.setLevel(logging.INFO)
file_handler = logging.FileHandler('export_log.csv',mode='w')
export_logger.addHandler(file_handler)
export_logger.info(",".join(['status', 'view', 'filename', 'stdout', 'stderr', 'time']))
Logging:
column_list = [status, view, filename, out, err, current_time]
message = ",".join([str(item) for item in column_list])
export_logger.info(message)
My problem is that if any of the strings contain a new line character or comma, it breaks the output. I could surround them in quotes, but then it would break if they contain quotes. I can escape those, but I'd rather not rewrite code for parsing all the edge cases of CSV file writing. Is there a good way to handle this?
Is there a way to easily sanitize strings for writing to CSVs? I could do this: How do I write data into csv format as string (not file)? But that seems very roundabout and unreadable.
I'm only using the logging library because I thought that was best practice, but if it can't handle CSV formatting I may as well just open a module level CSV file and write lines to it using the python csv library, right?