python3:logging.baseConfig是否将所有内容发送到stderr



以下死的简单代码:

import logging
import requests
logging.basicConfig(level=logging.DEBUG)
res = requests.get('https://www.stackoverflow.com')

python ./test.py > foo.txt一样运行会将所有内容发送到stderr。为什么这不会被stdout?

logging.basicConfig在未给定handler/filename/stream参数时使用StreamHandler,并且StreamHandler默认为STDERR流:

class StreamHandler(Handler):
def __init__(self, stream=None):
"""
Initialize the handler.
If stream is not specified, sys.stderr is used.
"""
Handler.__init__(self)
if stream is None:
stream = sys.stderr  # <- Here
self.stream = stream

要使用STDOUT,请将sys.stdout作为stream:传递

logging.basicConfig(level=logging.DEBUG, stream=sys.stdout)

现在,正如您目前所拥有的,您可以从类似外壳的中捕获STDERR

python ./test.py  2> foo.txt

因此重定向文件描述符2(即STDERR(就可以了

STDOUT是文件描述符1,当执行裸重定向>时,假定为1>

如果出于某种原因,你想使用不同的文件重定向两个流,你可以这样做:

python ./test.py  >stdout.txt 2>stderr.txt

如果您想将两者重定向到同一个文件:

python ./test.py  >all.txt 2>&1  # POSIX

python ./test.py  &>all.txt  # `bash`-ism (works in other advanced shells as well)

您需要将logging.StreamHandler()添加到根处理程序中,并将其配置为使用stdout

import logging
import requests
import sys
root = logging.getLogger()
root.setLevel(logging.DEBUG)
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.DEBUG)
root.addHandler(handler)
res = requests.get('https://www.stackoverflow.com')

最新更新