Search code examples
pythonloggingvimpython-mode

reset python interpreter for logging


I am new to Python. I'm using Vim with Python-mode to edit and test my code and noticed that if I run the same code more than once, the logging file will only be updated the first time the code is run. For example below is a piece of code called "testlogging.py"

#!/usr/bin/python2.7
import os.path
import logging

filename_logging = os.path.join(os.path.dirname(__file__), "testlogging.log")
logging.basicConfig(filename=filename_logging, filemode='w',
                level=logging.DEBUG)
logging.info('Aye')

If I open a new gvim session and run this code with python-mode, then I would get a file called "testlogging.log" with the content

INFO:root:Aye

Looks promising! But if I delete the log file and run the code in pythong-mode again, then the log file won't be re-created. If at this time I run the code in a terminal like this

./testlogging.py

Then the log file would be generated again!

I checked with Python documentation and noticed this line in the logging tutorial (https://docs.python.org/2.7/howto/logging.html#logging-to-a-file):

A very common situation is that of recording logging events in a file, so let’s look at that next. Be sure to try the following in a newly-started Python interpreter, and don’t just continue from the session described above:...

So I guess this problem with logging file only updated once has something to do with python-mode remaining in the same interpreter when I run a code a second time. So my question is: is there anyway to solve this problem, by fiddling with the logging module, by putting something in the code to reset the interpreter or by telling Python-mode to reset it?

I am also curious why the logging module requires a newly-started interpreter to work...

Thanks for your help in advance.


Solution

  • The log file is not recreated because the logging module still has the old log file open and will continue to write to it (even though you've deleted it). The solution is to force the logging module to release all acquired resources before running your code again in the same interpreter:

    # configure logging
    # log a message
    # delete log file
    
    logging.shutdown()
    
    # configure logging
    # log a message (log file will be recreated)
    

    In other words, call logging.shutdown() at the end of your code and then you can re-run it within the same interpreter and it will work as expected (re-creating the log file on every run).