I need to rename a logging file but continue logging to it afterwards. I'm running Python 3.x and using a logging
module to create logs.
logger = logging.getLogger(r'mylogger')
handler = logging.FileHandler(r'mylog.txt', mode = r'w')
logger.addHandler(handler)
logger.info(r'msg 1')
logger.info(r'msg 2')
handler.renameFile(r'my_newlog.txt') # <--- Is something like this possible?
logger.info(r'msg 3')
Does anyone know if something like this is possible? If no, how would I go about doing it? One idea that I had was to close the file (handler.close()
), remove the handler from the logger, rename the old file, create a new handler with the new file name and add it to the logger. The issue however is that I would need to create a completely identical handler, i.e it would need to have the same attributes as the old one (with exception of the file name of course). Is there a simple way to store old attributes and then use them to set the attributes of the new handler?
Any help is appreciated.
Late the party, but I ran into this problem as well and here's how I've (tentatively) solved it. Needs more testing though.
Note in my case, I do have access to the previous handler, so I just wound up using the same handler configuration I used earlier. I agree a FileHandler.'rename_file()' method would be great. One could likely be cooked up by sub-classing FileHandler(), but that's an exercise for another day.
#!/usr/bin/env python3
import os
import logging
logger_name1 = 'my_log.txt'
logger_name2 = 'my_new_log.txt'
logger = logging.getLogger('mylogger')
logger.level = logging.INFO
handler = logging.FileHandler(logger_name1, mode='w')
logger.addHandler(handler)
logger.info('msg 1')
logger.info('msg 2')
# handler.renameFile('my_newlog.txt') # <--- Is something like this possible?
logger.removeHandler(handler)
# Rename the logfile on disk
os.rename(logger_name1, logger_name2)
# New handler using new filename. Note the 'append' flag
new_handler = logging.FileHandler(logger_name2, mode='a')
logger.addHandler(new_handler)
# Try out the new logfile
logger.info('msg 3')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With