Writing in Python creates empty files
I am using python logger. I only need the log file generated if there is something to log. In other words, the log file should not be created if there was nothing to log.
As soon as
logging.basicConfig( filename=filename_log, level=logging.DEBUG, mode='w')
launched, an empty log file is created. I am trying to remove it before exiting:
if ( os.stat( filename_log ).st_size == 0 ): os.remove( filename_log)
which throws an error:
WindowsError: [Error 32] The process cannot access the file because it is being used by another process
So, I suppose there is more to do before.
So, is there a way to not create empty log files without writing my own logging routine?
In short:
logging.basicConfig( filename=filename_log, level=logging.DEBUG, mode='w')
logging.debug('This message should go to the log file')
writes correctly, but gives an empty file if nothing needs to be logged. AND
with open( filename_log, 'w') as logfile:
logging.basicConfig( stream=logfile, level=logging.DEBUG)
gives: ValueError: I/O operation on closed file
source to share
I am not familiar with how Windows handles I / O. On a * nix system, I would assume that the I / O stream is not closed by the logging function that processes 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)
source to share