我有一个不错的日志记录设置,可以在其中创建详细的调试日志到文件,同时将干净的信息日志记录到stdout。我想混合使用“旋转日志”,因此我查看了以下建议:stack post(这正是我想要的)。问题是,我遇到与other stack post类似的问题。有人可以回答为什么在我的代码调用“ doRollover()”之后,日志仍被写入logtest.log.1吗?
#logtest
import sys, os, time, logging, logging.handlers
log_file = r'/logs/test/logtest.log'
needRoll = os.path.isfile(log_file)
rotater=logging.handlers.RotatingFileHandler(log_file, backupCount=5)
log = logging.getLogger()
logging.basicConfig(
filename=log_file,
level='DEBUG',
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
handlers=[rotater])
stdout_handler = logging.StreamHandler(sys.stdout)
stdout_handler.setLevel(logging.INFO)
log.addHandler(stdout_handler)
if needRoll:
log.debug("Log closed on %s." %time.asctime())
rotater.doRollover()
log.info('New Log!')
结果:
logtest.log = {空}
logtest.log.1 =
2019-02-25 14:15:01,372-根-调试-日志在2019年2月25日星期一14:15:01关闭。
2019-02-25 14:15:01,381-根-信息-新日志!
编辑:在约翰·安德森的指导下进行修复:
log_file = r'/logs/test/logtest.log'
needRoll = os.path.isfile(log_file)
log = logging.getLogger()
log.setLevel(logging.DEBUG)
rotater=logging.handlers.RotatingFileHandler(log_file, backupCount=5)
rotater.setLevel(logging.DEBUG)
rotater.setFormatter(logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s"))
log.addHandler(rotater)
stdout_handler = logging.StreamHandler(sys.stdout)
stdout_handler.setLevel(logging.INFO)
log.addHandler(stdout_handler)
if needRoll:
log.debug("Log closed for next run on %s." %time.asctime())
rotater.doRollover()
log.info('New Log!')
答案 0 :(得分:0)
John Anderson通过向我显示在basicConfig()函数中设置文件名可能会导致问题,从而为我指明了正确的方向。我改写了没有它的日志,它工作正常。
log_file = r'/logs/test/logtest.log'
needRoll = os.path.isfile(log_file)
log = logging.getLogger()
log.setLevel(logging.DEBUG)
rotater=logging.handlers.RotatingFileHandler(log_file, backupCount=5)
rotater.setLevel(logging.DEBUG)
rotater.setFormatter(logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s"))
log.addHandler(rotater)
stdout_handler = logging.StreamHandler(sys.stdout)
stdout_handler.setLevel(logging.INFO)
log.addHandler(stdout_handler)
if needRoll:
log.debug("Log closed for next run on %s." %time.asctime())
rotater.doRollover()
log.info('New Log!')