1

I'm trying to have an exception handling mechanism with several layers of information to display to the user for my application, using python's logging module.

In the application, the logging module has 2 handlers: a file handler for keeping DEBUG information and a stream handler for keeping INFO information. By default, the logging level is set to INFO. What I'm trying to achieve is a setup where if any exception occurs, the user gets shown a simple error message without any tracebacks by default. If the logging level is set to DEBUG, the user should still get the simple message only, but this time the exception traceback is logged into a log file through the file handler.

Is it possible to achieve this?

I tried using logger.exception(e), but it always prints the traceback onto the console.

2 Answers 2

2

The traceback module may help you. At the top level of your application, you should put a catch all statement:

setup_log_and_other_basic_services()
try:
    run_your_app()
except Exception as e:
    if is_debug():
        traceback.print_stack()
    else:
        traceback.print_stack(get_log_file())
    print e

the code outside the try/catch block should not be allowed to crash.

Sign up to request clarification or add additional context in comments.

1 Comment

with this solution the traceback printed is the one starting in the except block, not the one starting from the exception. It doesn't really help localizing the source of the crash.
0

Write your custom exception handling function, and use it every time you write catch.

In this function you should check which mode is on (INFO or DEBUG) and then extract info about exception and feed it to logger manually when needed.

Comments

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.