Home > OS >  python logging: Any way to recreate log file while running when the opened file being deleted?
python logging: Any way to recreate log file while running when the opened file being deleted?

Time:08-31

The code snippet is as follows:

import logging
import time

logging.basicConfig(filename='test.log', filemode='a', format='...', datefmt='...', level=logging.INFO)
for i in range(0, 1000):
  time.sleep(1)
  logging.info('...')

After executing this python file, test.log is created as expected, yet when I delete this file while the python file is still running, test.log could not be recreate again as if it is writing to /dev/null later on.

Is there any way to detect the file being deleted and recreate test.log again from logging module? Thanks~

CodePudding user response:

Assuming an UNIX platform, it's not writing "as if to /dev/null", it's writing to that same test.log on disk (yes, with the implication that you could run out of disk space!).

You might know the actual name for a delete operation is unlink; indeed, if you "delete" the file, you just unlink the name from the directory it's in. As soon as the Python process closes the file descriptor (i.e. there are no more remaining references to the file) it'll actually be gone. (You can actually use tools such as lsof or the /dev/.../fd hierarchy to recover and re-link the file if you need to so long as it's still open.)

Anyway, to answer your question: instead of basicConfiging your logger, use logging.handlers.WatchedFileHandler:

The WatchedFileHandler class, located in the logging.handlers module, is a FileHandler which watches the file it is logging to. If the file changes, it is closed and reopened using the file name.

  • Related