0

I have the following code

class myclass(object):
    def __init__(self):
        self._fileA = os.path.join(dir, file)
        self._stuffA = 'NONE'

    def log(self, message):
        # Checks if the log file exists and if not creates a new one. 
        # Attempts to open the log file. If it cannot it raises an error
        try:
            log_file = open(self._fileA, 'ab')
        except IOError, e:
            print "!!! ERROR !!! - " + str(e)
            return 0

        now = datetime.datetime.now()
        # Sets up the date and the log file entry
        message = now.strftime("%Y-%m-%d %H:%M:%S") + ' - ' + str(message)
        # Writes the log entry then places a newline and closes the log file.
        log_file.write(logmsg)
        log_file.write('\n')
        log_file.close()

    def cleanup(self):
        logmsg = '----- ENDED SEARCH -----'
        self.log(logmsg)

Now this is just a snippet I left out quite a bit. But when the log function is being called from within my class. It just writes the last message to the file vice the new one being sent to it from the cleanup function. Any ideas on how to fix this?

4

1 回答 1

1

You write logmsg to the file, but never define it in your function:

    log_file.write(logmsg)

You must have a logmsg global that is being used instead.

Your actual message variable is called message, write that instead:

    log_file.write(message)
于 2012-11-23T17:30:48.083 回答