I'd like to change the log's directory depending on the time (specifically the hour) when new log is created.
For example, let's say the message aaa
is saved in a log file in directory d:\log\191105\09\log.log
at 09:59 during running a program.
As the time passes, new log bbb
is saved in a log file but the directory should be different, d:\log\191105\10.log
at 10:00 without terminating the program.
My log manager code is following,
import logging
import datetime
import psutil
import os, os.path
class LogManager:
today = datetime.datetime.now()
process_name = psutil.Process().name()
process_id = str(psutil.Process().pid)
log_dir = "D:/LOG/" + today.strftime("%Y%m%d") + "/" + today.strftime("%H") + "/"
log_filename = process_name + '_[' + process_id + ']_' + today.strftime("%Y-%m-%d_%H") + '.log'
if not os.path.exists(log_dir):
os.makedirs(log_dir)
# date/directory config
log = logging.getLogger('mypython')
log.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s||%(levelname)s||%(message)s')
fileHandler = logging.FileHandler(log_dir+log_filename)
fileHandler.setFormatter(formatter)
log.addHandler(fileHandler)
def update(self):
self.today = datetime.datetime.now()
old_log_dir = self.log_dir
self.log_dir = "D:/LOG/" + self.today.strftime("%Y%m%d") + "/" + self.today.strftime("%H") + "/"
if (old_log_dir == self.log_dir):
return
self.log_filename = self.process_name + '_[' + self.process_id + ']_' + self.today.strftime("%Y-%m-%d_%H") + '.log'
if not os.path.exists(self.log_dir):
os.makedirs(self.log_dir)
self.log = logging.getLogger('mypython')
# here, i wanna update my filehandler
for hdlr in self.log.handlers[:]:
if isinstance(hdlr, self.log.FileHander):
self.log.removeHandler(hdlr)
self.fileHandler = logging.FileHandler(self.log_dir+self.log_filename)
self.fileHandler.setFormatter(self.formatter)
self.log.addHandler(self.fileHandler)
def i(self, ex):
self.update()
self.log.info(ex)
def w(self, ex):
self.update()
self.log.warning(ex)
and I call these functions like
import LogManager as lm
logManager = lm.LogManager()
logManager.i('message')
It works well, but seems like it does not update its fileHandler after passing the hour.
I tried to find if the log has updateHandler method... but it doesn't .
What should I do??