Repeated output when logging exceptions

John Gordon gordon at panix.com
Thu Sep 24 21:43:14 CEST 2009


I wrote some code to handle and log exceptions in my application.
It works well, but it produces double output for each exception.
How can I fix this?

Here's the pared-down code:

----- main.py
import exceptionLogger
import doStuff

exlog = exceptionLogger.exceptionLogger()

stuff = doStuff.doStuff()

try:
    stuff.doit()
except Exception,msg:
    exlog.logException()


----- exceptionLogger.py
import traceback
import logging
import os

class exceptionLogger:
    loggingLevel = ""
    logger = None

    def __init__(self):
        self.logger = logging.getLogger("foo")
        self.loggingLevel = "DEBUG"
        if self.loggingLevel == "DEBUG":
            self.logger.setLevel(logging.DEBUG)
        handler = logging.FileHandler("error.txt")
        format = "%(asctime)s %(levelname)-8s %(message)s"
        formatter = logging.Formatter(format)
        handler.setFormatter(formatter)
        self.logger.addHandler(handler)

    def logMsg(self,message):
        try:
            if self.loggingLevel == "DEBUG":
                self.logger.debug(message)
        except:
            self.stopLogging()

    def logException(self):
        """Write an exception traceback to the logfile."""
        # save the stack trace to a file and then copy the contents of that
        # file to the log.  (traceback.format_exc would allow us to avoid
        # using a temporary file, but it is not available in python 2.3)

        TMPFILE = os.tmpfile()
        traceback.print_exc(None, TMPFILE)
        TMPFILE.flush()
        self.logMsg(" ************** EXCEPTION BEGINS **************")
        self.logMsgFromFile(TMPFILE)
        self.logMsg(" ************** EXCEPTION ENDS   **************")

        TMPFILE.close()

    def logMsgFromFile(self,file):
        """Read the contents of a file into a string and log the string."""
        file.seek(0)
        msg = ""
        for line in file:
            msg = msg + line
        self.logMsg(msg)

    def stopLogging(self):
        logging.shutdown()

----- doStuff.py
import exceptionLogger

class doStuff:

    def doit(self):
        exlog = exceptionLogger.exceptionLogger()
        try:
            raise ValueError, "hi there"
        except Exception:
            exlog.logException()


And here's the contents of error.txt:

----- errror.txt
2009-09-24 14:22:23,288 DEBUG     ************** EXCEPTION BEGINS **************
2009-09-24 14:22:23,288 DEBUG     ************** EXCEPTION BEGINS **************
2009-09-24 14:22:23,288 DEBUG    Traceback (most recent call last):
  File "/home/gordonj/exception/doStuff.py", line 8, in doit
    raise ValueError, "hi there"
ValueError: hi there

2009-09-24 14:22:23,288 DEBUG    Traceback (most recent call last):
  File "/home/gordonj/exception/doStuff.py", line 8, in doit
    raise ValueError, "hi there"
ValueError: hi there

2009-09-24 14:22:23,288 DEBUG     ************** EXCEPTION ENDS   **************
2009-09-24 14:22:23,288 DEBUG     ************** EXCEPTION ENDS   **************


As you can see, all of the output is doubled.  Header lines, footer lines,
and body text.

Why is this happening?  I suspect it's because I'm declaring two instances
of the exceptionLogger class, which ends up calling logger.addHandler()
twice.  Is that right?

What would be a better way to handle this?

Thanks.

-- 
John Gordon                   A is for Amy, who fell down the stairs
gordon at panix.com              B is for Basil, assaulted by bears
                                -- Edward Gorey, "The Gashlycrumb Tinies"




More information about the Python-list mailing list