【发布时间】:2017-11-21 23:37:57
【问题描述】:
目前,这就是我所拥有的 (testlog.py):
import logging
import logging.handlers
filename = "example.log"
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
handler = logging.handlers.RotatingFileHandler(filename, mode = 'w', backupCount = 5)
handler.setLevel(logging.DEBUG)
handler.setFormatter(formatter)
logger.addHandler(handler)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setFormatter(formatter)
logger.addHandler(ch)
for i in range(10):
logger.debug("testx") #where I alternate x from 1 thru 9 to see output
它目前已成功打印到控制台和example.log,这正是我想要的。
每次我运行它时,它都会生成一个新文件并替换旧的example.log,如下所示:
-
使用
logger.debug("test1")运行 -example.log将包含test110 次。 -
使用
logger.debug("test2")运行 - 它会重写example.log以包含test210 次。 -
等等……
但是,我希望代码在每次运行程序时创建一个新的日志文件,这样我就有:
example.log
example.log1
example.log2
...
example.log5
总之,我希望这个文件将日志消息打印到控制台、日志文件,并且每当我运行程序时我都想要一个新的日志文件(最多 *.5)。
【问题讨论】:
-
已解决!我所做的只是在末尾添加
logging.handlers.RotatingFileHandler.doRollover(handler) -
不要在最后做——如果你的脚本在中点结束时失败,你将不会在下一次开始时获得新的日志文件。在初始化日志记录时执行此操作。
标签: python logging python-logging