I’m learning how to use the python logging module and wanted to know if it’s possible to split the code below so the variables are easily readable and identified:
formatter_f = logging.Formatter('%(asctime)s,%(levelname)s,%(module)s,%(funcName)s,%(message)s',datefmt='%m/%d/%Y %H:%M:%S')
which results in:
03/25/2022 09:51:28,WARNING,main,<module>,first
03/25/2022 09:51:28,ERROR,sub2,div,error happened: division by zero
03/25/2022 09:51:28,WARNING,main,<module>,done
I tried to do a more pep8 style with this:
formatter_f = logging.Formatter('%(asctime)s,\
%(levelname)s,\
%(module)s,\
%(funcName)s,\
%(message)s',
datefmt='%m/%d/%Y %H:%M:%S')
but it produced this:
03/25/2022 10:01:32, WARNING, main, <module>, first
03/25/2022 10:01:32, ERROR, sub2, div, error happened: division by zero
03/25/2022 10:01:32, WARNING, main, <module>, done
I also tried to set each part as it own variable so i could set a sinlge master sting and keep each var on it’s own line, like
asctime = "asctime"
levelname="levelname"
module="module"
funcName="funcName"
message="message"
date_format = "%m/%d/%Y %H:%M:%S"
file_format_string =f"%({asctime})s,%({levelname})s,%({module})s,%({funcName})s,%({message})s', datefmt={date_format}"
formatter_f = logging.Formatter(file_format_string)
When the program ran nothing was logged to the file and this error showed up in console:
TypeError: not enough arguments for format string
Is there a way to organize the logging.Formatter() with each var on its own line or am I stuck with this being a single huge line?
>Solution :
You can use a sequence of adjacent string literals, which will automatically be concatenated by the compiler.
formatter_f = logging.Formatter('%(asctime)s,'
'%(levelname)s,'
'%(module)s,'
'%(funcName)s,'
'%(message)s',
datefmt='%m/%d/%Y %H:%M:%S')