I would like to disable the stack trace that is printed when there is an exception raised.
Asked
Active
Viewed 8,018 times
6
-
1There are no security reasons for disabling the stack trace. – Apr 22 '13 at 17:16
-
the reason is not so important so I removed it. – Adam Oren Apr 22 '13 at 17:18
-
possible duplicate of [Python Global Exception Handling](http://stackoverflow.com/questions/6598053/python-global-exception-handling) – Amber Apr 22 '13 at 17:18
-
That doesn't solve what I'm worried about (you assuming it is beneficial for security). – Apr 22 '13 at 17:19
-
1This question is not about security – Adam Oren Apr 22 '13 at 17:20
-
1I get that, but you wouldn't be the first to ask a question based on a faulty premise and would benefit more from correcting that assumption. – Apr 22 '13 at 17:22
-
Purely out of interest, what reason do you have? – Gareth Latty Apr 22 '13 at 17:24
-
I would like to remove stack trace information from the log on production environment – Adam Oren Apr 22 '13 at 18:54
2 Answers
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
-
1Please 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
-
2bruno, 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