繁体   English   中英

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

[英]Python logger - Redirecting STDOUT to logfile as well as any debug messages

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

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

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

基于这个答案,这是我的示例代码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时,我得到这个 output:

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

所以我实际上得到了与我想要的相反的结果:日志文件排除了我希望包含它们的 STDOUT 打印,程序 output 包含了我希望排除它们的调试消息。

我该如何解决这个问题,以便运行test.py仅输出print语句中的行,而生成的debug.log文件包含 DEBUG 日志和打印行?

好吧,我可以让它工作,但我还不知道是否会因此产生任何影响。 也许其他人能够指出任何潜在的陷阱,例如多线程。

您可以将sys.stdout设置为您喜欢的任何文件,例如 object。 这将包括您的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

您可以删除处理连接到标准输出的sh的代码。

我认为您不希望所有stdout output 都进入日志文件。

您可以做的是将控制台处理程序的日志记录级别设置为logging.INFO并将文件处理程序的日志记录级别设置为logging.DEBUG 然后将您的print语句替换为对logging.info的调用。 这种方式只有信息消息及以上将是 output 到控制台。

像这样的东西:

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

演示

如果您真的希望所有output 到stdout最终都出现在日志文件中,请参阅例如mhawke 的答案以及链接的问题和答案。

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

下面,我定义了一个自定义日志级别,其值高于logging.CRITICAL ,因此我们的控制台 output 始终会打印,即使记录器的级别是CRITICAL 请参阅文档

这是基于 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}')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM