记录器配置记录到文件并打印到stdout [英] logger configuration to log to file and print to stdout

查看:161
本文介绍了记录器配置记录到文件并打印到stdout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Python的日志记录模块将一些调试字符串记录到一个非常好的文件。此外,我想使用此模块也可以将字符串打印到stdout。我该怎么做?为了将我的字符串记录到文件中,我使用以下代码:

I'm using Python's logging module to log some debug strings to a file which works pretty well. Now in addition, I'd like to use this module to also print the strings out to stdout. How do I do this? In order to log my strings to a file I use following code:

import logging
import logging.handlers
logger = logging.getLogger("")
logger.setLevel(logging.DEBUG)
handler = logging.handlers.RotatingFileHandler(
    LOGFILE, maxBytes=(1048576*5), backupCount=7
)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)

然后调用logger函数,如

and then call a logger function like

logger.debug("I am written to the file")

感谢您的帮助!

推荐答案

处理根记录器并添加StreamHandler。 StreamHandler写入stderr。不知道如果你真的需要stdout stderr,但这是我在设置Python日志记录器时使用的,我也添加了FileHandler。然后我所有的日志都到达这两个地方(这听起来像你想要的)。

Just get a handle to the root logger and add the StreamHandler. The StreamHandler writes to stderr. Not sure if you really need stdout over stderr, but this is what I use when I setup the Python logger and I also add the FileHandler as well. Then all my logs go to both places (which is what it sounds like you want).

import logging
logging.getLogger().addHandler(logging.StreamHandler())

您还可以添加一个Formatter所以所有的日志行都有一个共同的标题。

You could also add a Formatter to it so all your log lines have a common header.

ie:

import logging
logFormatter = logging.Formatter("%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s]  %(message)s")
rootLogger = logging.getLogger()

fileHandler = logging.FileHandler("{0}/{1}.log".format(logPath, fileName))
fileHandler.setFormatter(logFormatter)
rootLogger.addHandler(fileHandler)

consoleHandler = logging.StreamHandler()
consoleHandler.setFormatter(logFormatter)
rootLogger.addHandler(consoleHandler)

打印格式为:

2012-12-05 16:58:26,618 [MainThread  ] [INFO ]  my message

这篇关于记录器配置记录到文件并打印到stdout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆