从 Python 库输出错误信息的正确方法

The right way to output an error message from a Python library

现在我的 Python 代码中有:

sys.stderr.write("Iteration stopped to avoid infinite loop.\n")

但是无论代码的客户端想要什么,这段代码总是写入 stderr。

我会改用记录器,但这会向 stderr 输出如下消息:

:INFO:main:Iteration stopped to avoid infinite loop.

而不是

Iteration stopped to avoid infinite loop.

我不想 :INFO:main: 收到这条消息。

所以我的问题:

如果Python安装中没有这样的class,那么我自己的记录器class的界面应该是什么?是不是应该像

class MyLogger(object):
    @abstractmethod
    def log(msg):
        pass

或者我可能错过了什么(也许添加一些其他方法,也许一些额外的 log() 参数)?

您可以修改basicConfig来更改错误信息

import logging
logging.basicConfig(format='%(message)s')
logging.warning("Iteration stopped to avoid infinite loop.")