1

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!

tripleee
192k37 gold badges319 silver badges370 bronze badges
asked Jun 7, 2021 at 17:16

2 Answers 2

1

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)
 
answered Jun 7, 2021 at 17:25
Sign up to request clarification or add additional context in comments.

1 Comment

Or logging.exception(e). See stackoverflow.com/questions/5191830/…
0

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)
answered Jun 7, 2021 at 17:43

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.