Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python logging creates empty files

Tags:

python

logging

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

like image 794
user1638775 Avatar asked May 12 '15 08:05

user1638775


Video Answer


1 Answers

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)
like image 135
Eli Korvigo Avatar answered Sep 30 '22 04:09

Eli Korvigo