Python – Maintaining log stream after file name change

file handlingloggingpython

I'm trying to log to a file and move it about every 30 seconds. I'm using the os.rename function (which I do from a supervisord process) in python to move the current log to a timestamped log (which will then be processed by another python script) and then I continue to log to the old stream from my uwsgi server.

I've also tried the RotatingFileHandler and the timed version, but they don't seem to work properly. I wasn't sure if that was a function of using it with the uwsgi server or not.

My question is, what is the simplest and most efficient way to continue logging to the same file name after the file it was "pointing to" has been moved?

Best Answer

Once Python opens a filehandle, it will continue to point to that file even if the file is renamed. (This is OS specific behavior, but that is the POSIX defined behavior for Unix.)

Therefore you either need to do the log rotation from inside of the Python process, or else make the file that you write to be a named pipe that itself handles log rotation. The latter is probably easier to set up. http://www.linuxjournal.com/article/2156 is an old, but still relevant, article on how to do this under Unix.