Search code examples
python-2.7loggingfile-rename

Renaming the log file at the end


In the beginning of the program the log file is named as:

filename='D://my_code_3/logging/'+timestr+'_XFR.log'

###set up logging to file
logging.basicConfig(level=logging.DEBUG,format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',datefmt='%m-%d %H:%M',filename='D://my_code_3/logging/'+timestr+'_XFR.log', filemode='w')

During the execution of the program, various entries are made in this log file.

At the end of the program, it is required to rename the log file, to include a unique str variable (str9)captured by the program (which was initially unavailable at the beginning of the program execution, when the log file was just created). In order to rename the log file at the end of the program, the old_name log file has to be closed at first. I included these instructions in the following code:

fh = open('D://my_code_3/logging/'+timestr+'_XFR.log', "r")
print fh.read()
fh.close()

Then at the very end, I ask for a rename as below:

old_file ='D://my_code_3/logging/'+timestr+'_XFR.log'
new_file = 'D://my_code_3/logging/'+timestr+''+str9+'_XFR.log'
os.rename(old_file, new_file)

I get the following error message:

`

Traceback (most recent call last): File "qar_xfr_2017_10_05_WIP.py", line 283, in os.rename(old_file, new_file) WindowsError: [Error 32] The process cannot access the file because it is being used by another process`

I think that the old_file is still being written, and hence the message that th e file is open. If so, how can i provide a time delay before attempting to rename the old_file?

Thanks in advance for correcting / suggestion a solution.


Solution

  • All handlers need to be closed properly by calling

    logging.shutdown()
    

    After that you can rename the log file.