Python记录器将STDOUT重定向到日志文件以及任何调试消息

2024-04-28 05:50:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在Python中使用日志模块,以便在运行程序时,得到一个日志文件debug.log,其中包含:

  1. 每个日志消息(logging.DEBUG、logging.WARNING等)
  2. 每次我的代码把东西打印到STDOUT

当我运行程序时,我只希望调试消息出现在日志文件中,而不是打印在终端上

基于this answer,下面是我的示例代码test.py

import logging
import sys

root = logging.getLogger()
root.setLevel(logging.DEBUG)

fh = logging.FileHandler('debug.log')
fh.setLevel(logging.DEBUG)

sh = logging.StreamHandler(sys.stdout)
sh.setLevel(logging.DEBUG)

formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
sh.setFormatter(formatter)
fh.setFormatter(formatter)

root.addHandler(sh)
root.addHandler(fh)

x = 4
y = 5
logging.debug("X: %s", x)
logging.debug("Y: %s", y)
print("x is", x)
print("y is", y)
print("x * y =", x*y)
print("x^y =", x**y)

下面是我想要的debug.log的内容:

2021-02-01 12:10:48,263 - root - DEBUG - X: 4                            
2021-02-01 12:10:48,264 - root - DEBUG - Y: 5
x is 4
y is 5
x * y = 20
x^y = 1024

相反,debug.log的内容只是前两行:

2021-02-01 12:10:48,263 - root - DEBUG - X: 4                            
2021-02-01 12:10:48,264 - root - DEBUG - Y: 5

当我运行test.py时,我得到以下输出:

2021-02-01 12:17:04,201 - root - DEBUG - X: 4
2021-02-01 12:17:04,201 - root - DEBUG - Y: 5
x is 4
y is 5
x * y = 20
x^y = 1024

所以我实际上得到了与我想要的相反的结果:日志文件在我想要的地方排除标准输出,程序输出在我想要排除的地方包括调试消息

如何修复此问题,以便运行test.py只输出print语句中的行,并且生成的debug.log文件同时包含调试日志和打印行


Tags: 文件pydebugtest程序log消息is
3条回答

我认为您不希望所有的stdout输出都进入日志文件

您可以将控制台处理程序的日志记录级别设置为logging.INFO,将文件处理程序的日志记录级别设置为logging.DEBUG。然后将print语句替换为对logging.info的调用。这样,只有信息和以上信息才会输出到控制台

大概是这样的:

import logging
import sys

logger = logging.getLogger(__name__)

console_handler = logging.StreamHandler(sys.stdout)
file_handler = logging.FileHandler("debug.log")
console_handler.setLevel(logging.INFO)
file_handler.setLevel(logging.DEBUG)

console_formatter = logging.Formatter('%(message)s')
file_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

console_handler.setFormatter(console_formatter)
file_handler.setFormatter(file_formatter)

logger.addHandler(console_handler)
logger.addHandler(file_handler)
logger.setLevel(logging.DEBUG) #set root logging level to DEBUG

if __name__ == "__main__":
    x = 4
    y = 5
    logger.debug("X: %s", x)
    logger.debug("Y: %s", y)
    logger.info("x is {}".format(x))
    logger.info("y is {}".format(y))
    logger.info("x * y = {}".format(x * y))
    logger.info("x^y = {}".format(x ** y))

Demo

如果您确实希望stdout的所有输出都在日志文件中结束,请参阅例如mhawke's answer,以及链接的问题和答案

但是,如果您真的对自己的print()调用的输出感兴趣,那么我将使用自定义日志级别将所有这些调用替换为Logger.log()调用。这使您可以对发生的事情进行细粒度的控制

下面,我定义了一个值高于logging.CRITICAL的自定义日志级别,因此始终打印控制台输出,即使记录器的级别为CRITICAL。见docs

下面是一个基于OP示例的最小实现:

import sys
import logging

# define a custom log level with a value higher than CRITICAL
CUSTOM_LEVEL = 100

# dedicated formatter that just prints the unformatted message
# (actually this is the default behavior, but we make it explicit here)
# See docs: https://docs.python.org/3/library/logging.html#logging.Formatter
console_formatter = logging.Formatter('%(message)s')

# your basic console stream handler
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setFormatter(console_formatter)

# only use this handler for our custom level messages (highest level)
console_handler.setLevel(CUSTOM_LEVEL)

# your basic file formatter and file handler
file_formatter = logging.Formatter(
    '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
file_handler = logging.FileHandler('debug.log')
file_handler.setFormatter(file_formatter)
file_handler.setLevel(logging.DEBUG)

# use a module logger instead of the root logger
logger = logging.getLogger(__name__)

# add the handlers
logger.addHandler(console_handler)
logger.addHandler(file_handler)

# include messages with level DEBUG and higher
logger.setLevel(logging.DEBUG)

# NOW, instead of using print(), we use logger.log() with our CUSTOM_LEVEL
x = 4
y = 5
logger.debug(f'X: {x}')
logger.debug(f'Y: {y}')
logger.log(CUSTOM_LEVEL, f'x is {x}')
logger.log(CUSTOM_LEVEL, f'y is {y}')
logger.log(CUSTOM_LEVEL, f'x * y = {x*y}')
logger.log(CUSTOM_LEVEL, f'x^y = {x**y}')

嗯,我可以让它工作,但我还不知道是否有任何影响,由于它。也许其他人能够指出任何潜在的陷阱,比如多线程

您可以将sys.stdout设置为您喜欢的任何类似文件的对象。这将包括logging.FileHandler()正在写入的文件。试试这个:

fh = logging.FileHandler('debug.log')
fh.setLevel(logging.DEBUG)

old_stdout = sys.stdout    # in case you want to restore later
sys.stdout = fh.stream     # the file to which fh writes

您可以删除处理连接到stdout的sh的代码

相关问题 更多 >