python中的Logger模块不会创建多个文件

时间:2019-07-16 07:29:51

标签: python class logging

我正在创建对象时使用对象唯一标签的唯一名称创建记录器。我想要不同对象的不同日志文件。它仅创建单个文件并将所有日志附加到该文件

我创建了5个班级学生实例,标签从1到6递增 在构造函数( init )中,我通过将标签附加到其上来创建具有唯一名称的logger对象。运行后,仅创建一个文件,而不是预期的5个单个文件

#python2.7
import logging
class student:
    def __init__(self,label):
        self.label = label
        file_name ="Log_Rollno" + str(self.label)
        logging.basicConfig(filename=file_name,format='%(asctime)s %(message)s',filemode='w')
        print "CREATED " + file_name
        self.logger = logging.getLogger()
        self.logger.setLevel(logging.DEBUG)
        self.logger.info("Message from Object" + str(self.label))

if __name__ == "__main__":
    for i in range(1,6):
        student_obj = student(i)

我希望:按照对象唯一标签(Log_Rollno1,Log_Rollno2)的单个文件

实际结果:来自所有已创建对象的消息仅被附加到一个文件中

(文件名:Log_Rollno1) 2019-07-16 12:52:49,884来自Object1的消息 2019-07-16 12:52:49,890来自Object2的消息 2019-07-16 12:52:49,894来自Object3的消息 2019-07-16 12:52:49,898来自Object4的消息 2019-07-16 12:52:49,904来自Object5的消息

1 个答案:

答案 0 :(得分:2)

logging.basicConfig()只能使用一次。它配置root记录器,并且如果已经连接了处理程序,它将不执行任何操作而静默返回。

documentation指出:

  

如果根记录器已经为其配置了处理程序,则此功能不起作用。

在您的情况下,第一个实例将配置记录器。以后创建的实例将不会。

您可能想通过将Handler附加到记录器来手动配置记录器,而不是使用logging.basicConfig()

Example in the docs showing how to attach a handler.