简体   繁体   English

在python的记录器中分离stdout和stderr

[英]Separating stdout and stderr in python's logger

I'm using the following code to separate the errors/warnings from the info/debug messages: 我正在使用以下代码将错误/警告与info / debug消息分开:

import sys, logging

class StdErrFilter(logging.Filter):
    def filter(self, rec):
        return rec.levelno in (logging.ERROR, logging.WARNING)

class StdOutFilter(logging.Filter):
    def filter(self, rec):
        return rec.levelno in (logging.DEBUG, logging.INFO)

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

formatter = logging.Formatter('%(process)s - %(asctime)s - %(name)s - %(levelname)s - %(message)s')

h1 = logging.StreamHandler(sys.stdout)
h1.setLevel(logging.DEBUG)
h1.setFormatter(formatter)
h1.addFilter(StdOutFilter())
logger.addHandler(h1)

h2 = logging.StreamHandler(sys.stderr)
h2.setLevel(logging.WARNING)
h2.setFormatter(formatter)
h2.addFilter(StdErrFilter())
logger.addHandler(h2)

unfortunately it looks like the filters are getting ignored. 不幸的是,看起来过滤器被忽略了。 Both files contain INFO/DEBUG messages... Any ideas? 这两个文件都包含INFO / DEBUG消息......有什么想法吗?

In UNIX terminal sys.stdout and sys.stderr are the same, which means if you run this script, you will get this: 在UNIX终端中sys.stdoutsys.stderr是相同的,这意味着如果你运行这个脚本,你会得到这个:

(venv) 🍀  python a.py
5798 - 2017-05-10  - __main__ - DEBUG - A DEBUG message
5798 - 2017-05-10  - __main__ - INFO - An INFO message
5798 - 2017-05-10  - __main__ - WARNING - A WARNING message
5798 - 2017-05-10  - __main__ - ERROR - An ERROR message

As a matter of fact, maybe you need to redirect sys.stderr and sys.stdout to different files by running this command, you will find that they are actually separated: 事实上,也许您需要通过运行此命令将sys.stderrsys.stdout重定向到不同的文件,您会发现它们实际上是分开的:

(venv) ➜ python a.py  2>> error 1>> info
(venv) 🍀 cat error
5895 - 2017-05-10  - __main__ - WARNING - A WARNING message
5895 - 2017-05-10  - __main__ - ERROR - An ERROR message
(venv) 🍀 cat info
5895 - 2017-05-10  - __main__ - DEBUG - A DEBUG message
5895 - 2017-05-10  - __main__ - INFO - An INFO message

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

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