【发布时间】:2017-06-21 01:21:45
【问题描述】:
正在开发一个实现记录器功能的 Python 应用
这是我的代码,取自官方site:
import logging
#create logger
logger = logging.getLogger("simple_example")
logger.setLevel(logging.DEBUG)
#create console handler and set level to debug
fh = logging.RotatingFileHandler(MyFile, etc)
fh.setLevel(logging.DEBUG)
#create formatter
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s -
%(message)s")
#add formatter to fh
fh.setFormatter(formatter)
#add fh to logger
logger.addHandler(fh)
#"application" code
logger.debug("debug message")
logger.info("info message")
logger.warn("warn message")
logger.error("error message")
logger.critical("critical message")
这是文件中的输出:非常完美
2005-03-19 15:10:26,618 - simple_example - 调试 - 调试消息
2005-03-19 15:10:26,620 - simple_example - INFO - 信息消息
2005-03-19 15:10:26,695 - simple_example - 警告 - 警告消息
2005-03-19 15:10:26,697 - simple_example - 错误 - 错误消息
2005-03-19 15:10:26,773 - simple_example - CRITICAL - 关键消息
但是这里是终端的输出:
DEBUG:调试消息
INFO:信息消息
警告:警告信息
错误:错误信息
CRITICAL:关键信息
这让我抓狂,因为我无法在控制台中看到时间戳...
我也尝试过创建另一个处理程序:
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
并将其添加到记录器...
但我唯一得到的是记录器在控制台中的每个 msg 都打印两次...一个完全正常,一个错误,正如我在开始时解释的那样
【问题讨论】:
-
fh.setFormatter没有将格式化程序设置为logger,那么问题出在哪里? -
这就是问题所在,我希望 fh 以我设置的格式登录控制台,或者根本不登录控制台,而只登录文件...
-
您似乎复制了该页面上的第一个示例,而不是 Multiple handlers and formatters 可能让您更接近所需内容的示例
标签: python logging outputstream