6

I would like to disable the stack trace that is printed when there is an exception raised.

Adam Oren
  • 799
  • 1
  • 6
  • 18

2 Answers2

2

Whenever the code calls the logger.exception method, the stack trace is automatically printed. That's because the default value of the exc_info parameter of the .exception method is True.

See the source code:

def exception(msg, *args, exc_info=True, **kwargs):
    """
    Log a message with severity 'ERROR' on the root logger, with exception
    information. If the logger has no handlers, basicConfig() is called to add
    a console handler with a pre-defined format.
    """
    error(msg, *args, exc_info=exc_info, **kwargs)

To prevent this, you can send exc_info=False to the .exception method like this:

  try:
      raise Exception("Huston we have a problem!")
  except Exception as ex:
      logger.exception(f"Looks like they have a problem: {ex}", exc_info=False)

While this seems like working, it is bad to force users to write exc_info=False each time they use that method. Therefore, in order to take this burden from the shoulders of the programmers, you can monkey patch the .exception method and make it act like a regular .error method like this:

# somewhere in the start of your program
# money patch the .exception method
logger.exception = logger.error

  try:
      raise Exception("Huston we have a problem!")
  except Exception as ex:
      logger.exception(f"Looks like they have a problem: {ex}")
ramazan polat
  • 7,111
  • 1
  • 48
  • 76
1

Looking around I found the following solution / workaround:

sys.tracebacklimit = 0

Adam Oren
  • 799
  • 1
  • 6
  • 18
  • 1
    Please dont. Having tracebacks is a GoodThing(tm). See http://stackoverflow.com/questions/6598053/python-global-exception-handling and http://docs.python.org/3/library/logging.html#logging.Logger.exception for the right way to keep the traceback private. – bruno desthuilliers Apr 22 '13 at 17:36
  • 1
    What you actually want is a custom `sys.excepthook`. – Bakuriu Apr 22 '13 at 18:33
  • 2
    bruno, can you add an example for the way you can have an exception being logged without the stacktrace? you are welcome to add this as an answer to this question – Adam Oren Apr 23 '13 at 15:08