我创建了一个扩展logging.Logger的CustomLogger。我试图使用getLogger来实现我的记录器实例化。这是我的代码:
import os
import sys
import logging
import atexit
class CustomLogger(logging.Logger):
def __init__(self,name,logfile):
super().__init__(name, level=logging.DEBUG)
self.logfile_handler = logging.FileHandler(logfile)
self.logfile_handler.setLevel(logging.DEBUG)
self.logfile_handler.setFormatter(logging.Formatter('%(name)s | %(levelname)s | %(message)s'))
self.addHandler(self.logfile_handler)
atexit.register(logging.shutdown)
print("Created logger: " + name + " " + logfile)
mycustom = CustomLogger("cust","./cust.log")
mycustom.critical("from direct write") #CORRECTLY WRITES TO FILE
logging.getLogger("cust").critical("from getLogger") #FAILS TO WRITE TO FILE
如何使用getLogger写入mycustom实例化?
我的目的是在其他模块中使用logging.getLogger(" cust")来写入此记录器。
答案 0 :(得分:1)
logging.getLogger("cust")
默认尝试使用logging.Manager
,Manager
实例新记录器和Logger
类创建或创建,您可以通过调用logging.setLoggerClass
全局更改此值。如果您不想这样做,可以将记录器实例注册到Manager
:
class CustomLogger(logging.Logger):
def __init__(self,name,logfile):
super().__init__(name, level=logging.DEBUG)
...
self.manager.loggerDict[name] = self
显然,这是一个黑客攻击。