user1638775
user1638775

Reputation: 63

Python logging creates empty files

I am using python's logging facility. I only want a log file created if there is something to log. In other words, no log file should be created if there was nothing to log.

As soon as

logging.basicConfig( filename=filename_log, level=logging.DEBUG, mode='w')

is ran, an empty log file is created. I try to delete it before exiting with:

if ( os.stat( filename_log ).st_size == 0 ): os.remove( filename_log)

which gives an error message:

WindowsError: [Error 32] The process cannot access the file because it is being used by another process

So I suppose something else should be done before.

So, is there any way not to have empty log files generated without writing my own logging procedure?

In short:

logging.basicConfig( filename=filename_log, level=logging.DEBUG, mode='w')
logging.debug('This message should go to the log file')

does log properly but gives an empty file if there is nothing to be logged. And

with open( filename_log, 'w') as logfile:
    logging.basicConfig( stream=logfile, level=logging.DEBUG)

gives a: ValueError: I/O operation on closed file

Upvotes: 6

Views: 5099

Answers (1)

Eli Korvigo
Eli Korvigo

Reputation: 10493

I'm not familiar with the way Windows handles I/O. On a *nix system I would suggest that the I/O stream is not closed by the logging function that handles it.

logging.basicConfig( filename=filename_log, level=logging.DEBUG, mode='w')

...
logging.shutdown()
if os.stat(file_name).st_size == 0 : 
    os.remove(filename_log)

Upvotes: 6

Related Questions