OS: Win7x64 6.1.7601
py: 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit (AMD64)]

I was able to create a logging class that posts to a file; however, despite reading several tutorials and the traceback docs from python.org, and creating a 'handleError' method, I'm unable to get my code to log tracebacks to the same log file - they still go to stdout. What am I missing here?

Here's my application logger class along with an example to run it...

# test.py

import sys
import traceback
import logging
import logging.handlers

class AppLogger:
    """ Log event messages to appLog and userLog"""
    def __init__ (self, *args, **kwargs):
        LEVELS = {'-INFO': logging.INFO,
                  '-DEBUG': logging.DEBUG,
                  '-WARNING': logging.WARNING,
                  '-ERROR': logging.ERROR,
                  '-CRITICAL': logging.CRITICAL}

            LEVEL = sys.argv[1]
            LEVEL = '-ERROR'


        LOGFILE = kwargs.get('LOGFILE', 'Application.log')

        FORMAT = '%(asctime)s %(levelname)s %(message)s'

        FORMATTER = logging.Formatter(FORMAT)

        HANDLER = logging.FileHandler(LOGFILE, 'w')

        # Enable application logging on init...
        self.appLog = logging.getLogger(__name__)

        def handleError (self, record):
            """ Traceback emit() """
            with open(LOGFILE, 'a') as FILE:
                traceback.print_tb(record, file = FILE)

        logging.Handler.handleError = handleError

        self.appLog.info('Application logging initiated at {} level.\n\
#End AppLogger class

class myApp(AppLogger):
    def __init__ (self, *args, **kwargs):
        AppLogger.__init__(self, LOGFILE = 'myTestLog.log')
        self.appLog.info('Example of a log message.')

        print junk
# End myApp class

if __name__ == '__main__':
    app = myApp(False)

The file output of this should be...

c:\> python test.py -DEBUG

c:\> type myTestLog.log

2011-10-10 09:17:48,065 INFO Application logging initiated at -DEBUG level.
2011-10-10 09:17:48,065 INFO Example of a log message.

Traceback (most recent call last):
  File "temp.py", line 61, in <module>
    app = myApp(False)
  File "temp.py", line 57, in __init__
    print junk
NameError: global name 'junk' is not defined

However, only the manual log entries are showing up in the file, and the traceback is still being displayed in stdout.

Any help would be greatly appreciated!



Edited 5 Years Ago by RMWChaos: n/a


from the output of your program it is clear that you didn't define the variable junk

"NameError: global name 'junk' is not defined"


from the output of your program it is clear that you didn't define the variable junk

"NameError: global name 'junk' is not defined"

Yes, that was intentional in order to force a traceback. Trying to get that traceback to output into the logfile rather than to stdout.



This article has been dead for over six months. Start a new discussion instead.