Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable stack trace in python

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

like image 725
Adam Oren Avatar asked Nov 12 '22 06:11

Adam Oren


2 Answers

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}")
like image 60
Ramazan Polat Avatar answered Nov 14 '22 23:11

Ramazan Polat


Looking around I found the following solution / workaround:

sys.tracebacklimit = 0

like image 45
Adam Oren Avatar answered Nov 14 '22 22:11

Adam Oren