Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rename a log file in python using a logging module

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.

like image 610
flashburn Avatar asked Aug 27 '14 15:08

flashburn


1 Answers

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')
like image 163
JS. Avatar answered Sep 16 '22 12:09

JS.