Search code examples
pythonlogging

Best practice to write Python exception in a log file


I defined a log_text() function to print custom messages and write it in a log file. My project architecture is quite simple, with the main script calling functions from another file:

main.py
|
|--- functions.py -- log_text()

I would like to catch any Python exception and print them in the log file, to help future users. For now I embedded almost all operations of main in a try/except block like this:

import #...
class parameters():
  log_file_path = #path to the log file

prm = parameters()

try:
  #main code

except Exception as e:
  log_text(log_file_path, e)
  print(e)

I am used to do this for small portions of a code, but not the whole script like that. Is it the common practice? Is there a better way to write any exception to a log file?


Solution

  • What you have is fine, for the most part. To keep things simpler, I would define a single function that can be called in your try statement. (This function can allow for testing, as you can import your script and call the function under controlled circumstances.) If you aren't actually "handling" the exception, you should also either re-raise the exception, or explicitly terminate the script with a non-zero exit status so that the caller still knows there was an error.

    def main():
       ...
    
    
    if __name__ == '__main__':
        try:
            main()
        except Exception as e:
            log_test(log_file_path, e)
            print(e)
            sys.exit(1)
    

    To re-raise the exception, replace both print(e) and sys.exit(1) with a single raise statement.