我有两个日志类,它们应该在两个不同的文件上打印日志。
头等舱
import logging
class firstLog:
def __init__(self):
self.logger = logging.getLogger("my_logger1")
logging.basicConfig(format="%(asctime)s.%(msecs)06d:\n%(message)s\n", level=logging.DEBUG,
datefmt="%d/%m/%Y %H:%M:%S",
filename="filename1.log")
def printlog(self, msg, *args, **kwargs):
self.logger.debug(msg, *args, **kwargs)
第二课
import logging
class secondLog:
def __init__(self):
self.logger = logging.getLogger("my_logger2")
logging.basicConfig(format="%(asctime)s.%(msecs)06d:\n%(message)s\n", level=logging.DEBUG,
datefmt="%d/%m/%Y %H:%M:%S",
filename="filename2.log")
def printlog(self, msg, *args, **kwargs):
self.logger.debug(msg, *args, **kwargs)
我实例化了两个类,但是只写了filename1.log
log1 = firstLog()
log2 = secondLog()
log1.printlog("text1")
log2.printlog("text2")
我得到的是一个名为 filename1.log 的新文件被创建,并且包含
04/06/2021 08:57:04.000988:
text1
04/06/2021 08:57:04.000990:
text2
但我需要两个单独的文件
答案 0 :(得分:3)
logging.basicConfig()
只应用一次。
如果已经配置了 logging
,除非设置了 basicConfig()
,否则 force
不会做任何事情。 (source)
在您的情况下,您应该获得具有 logging.getLogger(name)
和不同名称的单独记录器。然后手动配置记录器。
答案 1 :(得分:2)
logging.basicConfig()
旨在在您的应用启动时运行一次,并将配置根记录器。
如果您需要将其他两个记录器的输出传送到其他地方,您将需要手动配置另外两个记录器(或者可能在根记录器上配置“路由”处理程序)。