0

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()
BruceWayne
  • 22,923
  • 15
  • 65
  • 110
  • 1
    Potentially useful post [here](https://stackoverflow.com/a/3850621/5858851). (Other answers on that question also mention the useful `atexit` module) – pault Mar 21 '19 at 18:58
  • @pault - Ah! That's perfect! Should have thought of that, clever workaround. I'll use that for sure. But I'm curious if there's something more specific to logging too that I could use. – BruceWayne Mar 21 '19 at 19:07

1 Answers1

1

Don’t use quit() It is not good practice as it exit the process even if logging framework did not flush.

Instead raise an Exception. In case you don’t want to see the exception error on the console. Throw a specific error messages and ignore it with try and except.

Lior Cohen
  • 5,570
  • 2
  • 14
  • 30
  • Thanks for that - I've been meaning to remove the `quit()`, as I figured it wasn't a good idea. I'll look in to how raising exceptions work and do that. :) – BruceWayne Mar 21 '19 at 19:10