python3:logging.basicConfig会将所有内容发送到stderr吗?

python3:logging.basicConfig会将所有内容发送到stderr吗?,python,python-3.x,Python,Python 3.x,下面是非常简单的代码: import logging import requests logging.basicConfig(level=logging.DEBUG) res = requests.get('https://www.stackoverflow.com') 像python./test.py>foo.txt那样运行会将所有内容发送到stderr。为什么这不去stdout?日志记录。当没有处理程序/文件名/流参数被给定,并且流处理程序默认为STDERR流时,basicConfig使

下面是非常简单的代码:

import logging
import requests

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

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

日志记录。当没有
处理程序
/
文件名
/
参数被给定,并且
流处理程序
默认为STDERR流时,basicConfig
使用
流处理程序

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

现在,正如您目前所做的那样,您可以从shell中捕获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


您需要向根处理程序添加
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')

仅重定向stdout、
2>
重定向stderr和
&>
这两个输出。这很有意义,如果我想维护两个流,我必须为stderr筛选error+。我想可能有一种快速的方法可以将error+建立到stderr,而不是stdout。
python ./test.py  &>all.txt  # `bash`-ism (works in other advanced shells as well)
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')