Reputation: 1101
I looking for some "best-practice" advice.
In my Python app I am using exceptions for controlling the flow of my program. But I am not sure where I should log the exception. My gut feeling says I should log it closest to where the exception is raised. But that results in some rather clunky code:
def a_deeper_level_function():
print("I am doing stuff, but it goes wrong. So raising.")
# but I also want to log here with the same message.
# so I put my msg in a separate variable to re-use it.
msg = "this is the logging and exception message"
_LOGGER.error(msg)
raise Exception(msg)
Any thoughts appreciated!
Upvotes: 1
Views: 235
Reputation: 362
If you manually raise exception and know where it's going to be, try
finalize
may work for you. It makes it easier to navigate between exceptions too.
def a_deeper_level_function():
try:
print("I am doing stuff, but it goes wrong. So raising.")
msg = "this is the logging and exception message"
raise Exception(msg)
finally:
_LOGGER.error(msg)
Upvotes: 0
Reputation: 395
In python, best practice is to use logging module to generate log file. And for exception handling always use try except block.
Try following approach:
import logging
def a_deeper_level_function():
try:
print("I am doing stuff, but it goes wrong. So raising.")
# but I also want to log here with the same message.
# so I put my msg in a separate variable to re-use it.
msg = "this is the logging and exception message"
_LOGGER.error(msg)
raise Exception(msg)
except Exception as e:
logging.info(e)
Upvotes: 1