1

I want to save ALL ERRORS into a file which means the errors outside an exception, also get in the log file.

for example import some module and in the begining of a script, set it to save the errors; something like this:

import blob
blob.save_errors(filename)

try:
  lst = ['a']
  print(lst[2]) # save this Error
except:
  pass

print(2/0) # also save this error
3
  • Like this - stackoverflow.com/questions/1508467/… Commented Feb 21, 2022 at 5:07
  • is only save the errors in exception block and should set it manual. Commented Feb 21, 2022 at 5:09
  • Logging module is a good place to start. It's built into standard library. Commented Feb 21, 2022 at 5:14

1 Answer 1

2

There is no easy automatic way to process all the exception, it contradict with exception handling idea.

One of solutions: we can log all uncatched exceptions like this way:

import sys
import logging

logger = logging.getLogger(__name__)
handler = logging.StreamHandler(stream=sys.stdout)
logger.addHandler(handler)

def handle_exception(exc_type, exc_value, exc_traceback):
    if issubclass(exc_type, KeyboardInterrupt):
        sys.__excepthook__(exc_type, exc_value, exc_traceback)
    else:
        logger.critical("Exception occured:", exc_info=(exc_type, exc_value, exc_traceback))

sys.excepthook = handle_exception

# Just to test
if __name__ == "__main__":
    raise Exception("Something happend!")

And to log all handled exception we need to all logging in except block:

try:
    ...
except:
    logger.error("Exception occured:", exc_info=(exc_type, exc_value, exc_traceback))
    ...

Other way to deal with exception is to handle them in top-level function. All non-handled exceptions from downstream functions will be processed in top-level except block:

def my_main_func():
    try:
        run_my_application_logic()
    except:
        # Logging
        logger.error("Exception occured:", exc_info=(exc_type, exc_value, exc_traceback))

def run_my_application_logic():
    first_step_of_app()
    second_step_of_app()
    third_step_of_app()


if __name__ == "__main__":
    my_main_func()
Sign up to request clarification or add additional context in comments.

2 Comments

well thanks, but the first solution doesn't save worl actually, just prints the error same as before (I want to save the errors in a file)
@DANIEL1475 looger can write log to file. You just need to properly configure logger. stackoverflow.com/questions/6386698/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.