简体   繁体   English

如何登录文件和标准输出

[英]How to log to file & stdout

I have the following logging set up: 我设置了以下日志记录:

import logging
logging.basicConfig(level=logging.DEBUG,
                format='[%(asctime)s] - %(funcName)s - %(message)s',
                datefmt='%a, %d %b %Y %H:%M:%S',
                filename='/tmp/affiliate.log',
                filemode='w')

How would I convert the following two statements -- which writes to the log file and then prints the output: 我将如何转换以下两个语句-写入日志文件,然后输出输出:

logging.debug('>>>>> 401 Error: Cannot download file')
print '>>>>> 401 Error: Cannot download file'

Into one logging statement that does both? 合并成一个日志记录,两者兼而有之?

You can't do it with just basicConfig (at least not in Python 2.7; 3.3 added new features, in particular the handlers parameter), but it's easy to set up the logger to write to two places. 您不能basicConfig做到这basicConfig (至少不是在Python 2.7中; 3.3添加了新功能,尤其是handlers参数),但是将记录器设置为写入两个位置很容易。 The Logging Cookbook explains how to do all kinds of things in full detail. 日志记录手册详细介绍了如何进行各种操作。

A few of the cookbook entries aren't fully explained, just demonstrated, but you can always look up the details in the logging docs. 尚没有完全解释其中的一些菜谱条目,只是进行了演示,但您始终可以在logging文档中查找详细信息。

The key thing you're looking for here is to create two handlers — a FileHandler('/tmp/affiliate.log') , and a StreamHandler(sys.stdout) . 您在这里寻找的关键是创建两个处理程序— FileHandler('/tmp/affiliate.log')StreamHandler(sys.stdout)

If you want the same format, log level, etc. in both the log file and stdout , one of the early examples in the cookbook does exactly this, except with stderr . 如果要在日志文件和stdout使用相同的格式,日志级别等,则本食谱的早期示例之一就是这样做的,除了stderr If you want different formats for each, the very next example does that . 如果每种格式都需要不同的格式, 那么下一个示例将这样做

So, instead of this: 因此,代替此:

logging.basicConfig(level=logging.DEBUG,
                format='[%(asctime)s] - %(funcName)s - %(message)s',
                datefmt='%a, %d %b %Y %H:%M:%S',
                filename='/tmp/affiliate.log',
                filemode='w')

Do this: 做这个:

logger = logging.getLogger('')
logger.setLevel(logging.DEBUG)
fh = logging.FileHandler('/tmp/affiliate.log')
sh = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter('[%(asctime)s] - %(funcName)s - %(message)s',
                               datefmt='%a, %d %b %Y %H:%M:%S')
fh.setFormatter(formatter)
sh.setFormatter(formatter)
logger.addHandler(fh)
logger.addHandler(sh)

Note that the second example I linked uses basicConfig to do everything it can do, then adds a second handler on top of it. 请注意,我链接的第二个示例使用basicConfig可以做的一切,然后在其上面添加第二个处理程序。 I think this is a little less clear, but if you want to do the same, you can do it. 我认为这还不太清楚,但是如果您要这样做,也可以做到。

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

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