为什么我的日志代码不起作用?

时间:2017-04-27 02:30:04

标签: python logging

我正在关注日志记录教程,我正在努力使代码示例工作:

log_this = logging.getLogger("Sample")
log_this.setLevel(logging.INFO)

the_f = logging.FileHandler("sample.log")

form = logging.Formatter("%(asctime)s (%name)s %(levelname)s %(message)s")
the_f.setFormatter(form)

log_this.addHandler(the_f)

log_this.warning("hi")

只有在未包含以下内容时才有效:

log_this.addHandler(the_f)

知道什么是错的吗?

1 个答案:

答案 0 :(得分:0)

您的代码的拼写错误更改为(%name)s%(name)s,并且效果良好:

form = logging.Formatter("%(asctime)s %(name)s %(levelname)s %(message)s")
the_f.setFormatter(form)

log_this.addHandler(the_f)

log_this.warning('debug message')
log_this.info('info message')

输出:

2017-04-27 .. Sample WARNING debug message
2017-04-27 .. Sample INFO info message