Hello,
Tom Bryan
tbryan at python.net
Sat Jul 21 21:43:18 EDT 2001
Alex wrote:
> Not really. There are some ways you could speed up the python code:
I'm also not really sure why one would want to do this, but...
> There's the additional problem that
> opening "err" will truncate the log file, and if an error occurs while
> you're writing the new version back, you could lose messages.
here's a version that makes a copy of the file before prepending a
new message to avoid that problem. It also uses seek to avoid having
to reopen the file handle repeatedly. Depending on the use, it might
be fast enough, and since it's wrapped in a class, one could keep
track of the number of messages written and automatically rotate
log files as they get large so that it's not reading and copying so
many lines.
Of course, you'd still be confusing all of us who are quite used to
log files that append the most recent message to the end of the file. :-)
import shutil
class Logger:
def __init__( self, filename ):
self.filename = filename
self.file = open( filename, 'w+' )
def log( self, message ):
# Make a copy in case we die in the middle of the next op
shutil.copyfile( self.filename, self.filename + '.bak' )
# Prepend the message to the beginning of the file
self.file.seek( 0 )
old = self.file.read()
self.file.seek( 0 )
self.file.write( message )
self.file.write( old )
self.file.flush()
def __del__( self ):
self.file.close()
if __name__ == '__main__':
aLogger = Logger( 'error.log' )
aLogger.log( 'message1\n' )
aLogger.log( 'message2\n' )
aLogger.log( 'message3\n' )
there's-more-than-one-way-to-do-it-ly yours
---Tom
More information about the Python-list
mailing list