Python log file in descending order

Question:

I have an application written in python that logs errors in a log file, I am using the python logging module

Example:

import logging
logging.basicConfig(filename='logsfilename.log',
                    level=logging.DEBUG,
                    format='%(asctime)s - %(levelname)s - %(message)s')
logging.error('error connecting to server')

This is working fine and the log file is logging the errors, which mean the last error is logged on the last line of the file.

is there some kind of setting where I can tell the logging module to always write at the top of the file, this way the last error is always on the first line.

Asked By: wadapav

||

Answers:

It is very inefficient to write to the front of a flle as others have said. Every single write will have to first seek to the front of the file and then insert the new data before the other data. The underlying I/O of your operating system is designed to make appends cheap.

That said, if you insist on doing it, look at the docs here Logging Handlers. You can implement your own version of logging.handlers.FileHandler that will seek to the beginning before each write. Then you could call logging.addHandler() and place an instance of your class. If you only care about the most recent 10 or so log entries you could even truncate the file before you write.

Answered By: Sean Perry
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.