I'm doing this by using the sys.excepthook function to override the default exception handling. I saw that if I run the program directly from the command line, it works fine, but if I try to import the file, then it does not work. It seems that the sys.excepthook function is unaware of the logging module. Here's an example:
#! / Usr / bin / env python2.7 import logging, sys logger = logging.getLogger () logger.setLevel (logging.DEBUG) logger.addHandler (logging .filehandler ("test.log")) print exceptions outside the handler: Logger =% S "% logger def handleException (excType, excValue, traceback): #global logger # This function does not work whether or not I include this line print in the" Exception Handler: Logger =% s "% Logger Logger ("Unwanted Exception", exc_info = (excType, excValue, traceback) sys.excepthook = handleException logger.debug ("start") asdf # creates an exception If I Let's run it from the command line Not ( ./loggingTest.py ), it works fine. The exception is logged, and I see this output: Exceptions outside the handler : Logger = & lt; logging. Root object 0x7f2022eab950 & gt; Exceptional handler inside: Logger = & lt; logging. 0x7f2022eab950 & gt; However, if I run Python interpreter and Attempt to import the file ( import loggingTest ), then it works weirdly, the exception is not logged and I see it Not: out the exception handler: logger = & lt; Logging. Logging object at 0x7f8ab04f3ad0 & gt; In the exception handler: Logger = Error in any sys.excepthook: Traceback (most recent call final): file "loggingTest.py", line 13, handleException logger.error ("Uncaught exception", exc_info = (excType, Excavalue, traceback)) AttributeError: Traceback (most recent call last) :: 'None Type' object is a specialty 'error' the original exception was the file "& lt; stdin & gt;"; Module & gt; line1, & lt; "LoggingTest.py" file, line 18, & lt; Module & gt; Asdf # Name An Exception Error: Name 'asdf' is not defined I can probably solve this problem by importing the logging module within sys.excepthook, but still Curious: Why is this happening?
I told this problem as a bug, so far someone has replied that Definitely there is a change between Python 2.7 and 2.7.1 and he thinks this is the expected behavior. They have made some such suggestions to log all exceptions:
def handleException (excType, excValue, traceback, logger = logger): logger Terror ("Unwanted Exception", exc_info = (excType, excValue, traceback) sys.excepthook = handleException
Comments
Post a Comment