Want datetime in logfile name
创建日志文件时,我希望名称包含datetime。
现在,在python中,你可以得到当前的datetime:
1 2 3 | >>> from datetime import datetime >>> datetime.now() datetime.datetime(2012, 2, 3, 21, 35, 9, 559000) |
str版本为
1 2 | >>> str(datetime.now()) '2012-02-03 21:35:22.247000' |
添加到日志文件名中不是一个很好的str !我希望我的日志文件是这样的:
1 | mylogfile_21_35_03_02_2012.log |
python能做些什么让这变得容易吗?注意,我将日志文件创建为
1 | fh = logging.FileHandler("mylogfile" + datetimecomp +".log") |
任何建议吗?
您还可以使用
1 2 | from logging.handlers import TimedRotatingFileHandler fh = TimedRotatingFileHandler('mylogfile', when='midnight') |
默认情况下,该格式将取决于滚动间隔:
The system will save old log files by appending extensions to the filename. The extensions are date-and-time based, using the strftime format
%Y-%m-%d_%H-%M-%S or a leading portion thereof, depending on the rollover interval.
但你可以修改它,如这里所示,做如下操作:
1 2 3 | from logging.handlers import TimedRotatingFileHandler fh = TimedRotatingFileHandler('mylogfile', when='midnight') fh.suffix = '%Y_%m_%d.log' |
您需要
1 2 | >>> datetime.now().strftime('mylogfile_%H_%M_%d_%m_%Y.log') 'mylogfile_08_48_04_02_2012.log' |
是的。看看datetime API,特别是
1 2 | from datetime import datetime print datetime.now().strftime("%d_%m_%Y") |
我们可以使用date .now()获取当前时间戳。下面是我用来创建带有时间戳-的日志文件的代码
1 2 3 4 5 6 7 8 | import logging from datetime import datetime LOG_FILENAME = datetime.now().strftime('D:/log/logfile_%H_%M_%S_%d_%m_%Y.log') for handler in logging.root.handlers[:]: logging.root.removeHandler(handler) logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG) logging.info('Forecastiong Job Started...') logging.debug('abc method started...') |
1 2 3 | from time import strftime fh = logging.FileHandler(strftime("mylogfile_%H_%M_%m_%d_%Y.log")) |
要打印
从
1 | print datetime.now().strftime("%H_%M_%d_%m_%Y") |