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
  • 175,061
  • 34
  • 275
  • 318
sanders
  • 911
  • 1
  • 11
  • 22

2 Answers2

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)
       
  • Or `logging.exception(e)`. See https://stackoverflow.com/questions/5191830/how-do-i-log-a-python-error-with-debug-information –  Jun 07 '21 at 17:30
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)
J.Smith
  • 362
  • 1
  • 10