I am learning about logging, and was wondering how I can always include some text before my .py
quits/exits/errors out.
If I run my script three times, I have a single log file that stores all the errors/info/etc. But I'd like to include something like this at the end of each .py execution:
--------- End of .PY Execution ---------
so when looking at the file, after running my script twice, I can see:
2019-03-21, ERROR [get_files.py:13] Timed out when trying to connect to 192.168.100.106
2019-03-21, ERROR [get_files.py:13] Timed out when trying to connect to 192.169.291.291
2019-03-21, ERROR [get_files.py:13] Timed out when trying to connect to 192.000.000.000
------------------ END OF .PY EXECUTION ------------------------------------------------------
2019-03-21, INFO [get_files.py:20] Some text here as info
------------------ END OF .PY EXECUTION ------------------------------------------------------
Here's a mockup of the script (ignore whether it actually would return those errors above in that order, mainly I use quit()
in some places, so simply adding logging.info("-------- END OF .PY EXECUTION -----------")
after main()
call won't work for all cases).
import logging
logging.basicConfig(filename=os.path.basename(__file__) + '.log',
level=logging.DEBUG,
format='%(asctime)s, %(levelname)s \
[%(filename)s:%(lineno)d] %(message)s',
datefmt='%Y-%m-%d')
def open_connection(ip):
# Do things
if someCondition:
logging.error("Timed out when trying to connect to " + ip)
quit()
else:
return something
def open_again():
if someOtherCondition:
logging.info("Some text here as info")
def main():
lst = [some list of ip addresses]
for ip in lst:
test = open_connection(ip)
open_again()
if __name__ == "__main__":
main()