为什么 python 在控制台中忽略了我的格式化程序?

Why is python ignoring my formatter in the console?

我正在开发实现记录器功能的 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 - DEBUG - debug message

2005-03-19 15:10:26,620 - simple_example - INFO - info message

2005-03-19 15:10:26,695 - simple_example - WARNING - warn message

2005-03-19 15:10:26,697 - simple_example - ERROR - error message

2005-03-19 15:10:26,773 - simple_example - CRITICAL - critical message

但是这里是终端的输出:

DEBUG: debug message

INFO: info message

WARNING: warn message

ERROR: error message

CRITICAL: critical message

这让我抓狂,因为我无法在控制台中看到时间戳...

我也试过创建另一个处理程序:

ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)

并将其添加到记录器...

但我唯一得到的是记录器在控制台中打印两次每条消息...正如我在开始时解释的那样,一个完全正确,一个错误

可以使用 StreamHandler 单独调整控制台输出,为此您还必须添加格式化程序:

#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)

ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setFormatter(formatter)
logger.addHandler(ch)

这是我用于登录文件和控制台的内容:

logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s\t%(message)s', datefmt='%m-%d %H:%M', filename=logfile, filemode='a')
# define a Handler which writes INFO messages or higher to the sys.stderr
console = logging.StreamHandler()
console.setLevel(logging.DEBUG)
# set a format which is simpler for console use
formatter = logging.Formatter('%(asctime)s %(levelname)s\t%(message)s')
# tell the handler to use this format
console.setFormatter(formatter)
# add the handler to the root logger
logging.getLogger('').addHandler(console)
# Now, we can log to the root logger, or any other logger. First the root...
logging.info('LOGGING PATH: %s', logfile)

然后你可以为文件和控制台设置相同的输出。

为此需要在记录器的基本配置中进行初始化:

logging.basicConfig(streamä0sys.stdout, level=logging.INFO, format=myFormat)

其中

myFormat= "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"