我有一个简单的日志记录设置:
def main()
# ....
# Create logger
logging.basicConfig(filemode='w', level=logging.DEBUG)
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
# Create file handler for DEBUG and above
fh1 = logging.FileHandler(__name__ + '.debug.log')
fh1.setLevel(logging.DEBUG)
# Create file handler for INFO and above
fh2 = logging.FileHandler(__name__ + '.info.log')
fh2.setLevel(logging.INFO)
# Create console handler with INFO and above
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
# Add all the handlers to the logger
logger.addHandler(fh1)
logger.addHandler(fh2)
logger.addHandler(ch)
# ....
然后当我打电话时
logger.info("this is an INFO message")
logger.debug("this is a DEBUG message")
我在控制台上得到以下信息:
this is an INFO message
INFO:__main__:this is an INFO message
this is a DEBUG message
DEBUG:__main__:this is a DEBUG message
尽管我预计只会在控制台中看到 INFO
消息(因为我在上面为 StreamHandler
指定了 logging.info
)。为什么我会收到这些重复项?
我的 .debug.log
和 info.log
文件仅包含正确级别的消息,但它们的格式不包含前缀 INFO:__main__
也不是DEBUG:__main__
。为什么它们的格式不同?
最佳答案
logging.basicConfig(filemode='w', level=logging.DEBUG)
创建一个StreamHandler
。因此,您的代码将创建两个 StreamHandlers
,一个具有日志记录级别 DEBUG
,另一个具有日志记录级别 INFO
。
basicConfig
是一个便利函数。如果您想创建自己的处理程序,则无需调用 basicConfig
。 (或者您可以调用 basicConfig
并添加其他处理程序...)
如果您在调用 basicConfig
时未提供文件名,则会将 StreamHandler
添加到根记录器中。这是代码inside the basicConfig
function :
if handlers is None:
filename = kwargs.get("filename")
if filename:
mode = kwargs.get("filemode", 'a')
h = FileHandler(filename, mode)
else:
stream = kwargs.get("stream")
h = StreamHandler(stream)
关于python - 使用 Python 进行日志记录。处理程序和控制台副本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24540479/