打印日志并同时存储日志,我的代码怎么了?

2024-04-19 20:41:26 发布

您现在位置:Python中文网/ 问答频道 /正文

#!/usr/bin/python
import os 
import logging
import pickle

def _config_logger(test_name):
    logger = logging.getLogger()
    logger.setLevel(logging.DEBUG)
    logging.basicConfig(format='%(message)s',filename="./%s.txt" %(test_name))
    stderrLogger=logging.StreamHandler()
    stderrLogger.setFormatter(logging.Formatter('%(message)s'))
    logging.getLogger("").addHandler(stderrLogger)
    return logger

for i in ['x','y','z']:
    logger=_config_logger(i)
    logger.debug(i)

不需要输出,y打印两次,z打印3次。你知道吗

$Python测试.py
x


z
z
z轴

但是我只有一个文件x.txt,我希望是y.txt。z、 那是什么

$升 测试.pyx、 文本

我该怎么办?你知道吗


Tags: nametestimporttxtconfigmessagebinos
2条回答

检查文档中的logging.basicConfig

This function does nothing if the root logger already has handlers configured for it.

在为x.txt调用它一次以登录到之后,后续调用将不起作用。你知道吗

不要调用logging.basicConfig,而是添加一个与添加流处理程序类似的文件处理程序:

file_handler = logging.FileHandler("./%s.txt" %test_name)
file_handler.setFormatter(logging.Formatter('%(message)s'))
logger.addHandler(file_handler)

此处:

def _config_logger(test_name):
    logger = logging.getLogger()

您不会将test_name传递给geLogger(),因此您总是得到根记录器。几句话之后:

logging.getLogger("").addHandler(stderrLogger)

您不断向根记录器添加处理程序,因此出现了“y打印两次,z打印三次”症状。你知道吗

而且,多次调用.basicConfig()是没有用的,只有第一个调用是相关的,cfthe fine manual

Does basic configuration for the logging system by creating a StreamHandler with a default Formatter and adding it to the root logger. The functions debug(), info(), warning(), error() and critical() will call basicConfig() automatically if no handlers are defined for the root logger.

This function does nothing if the root logger already has handlers configured for it.

相关问题 更多 >