python - 跨子模块记录——如何从子模块访问父记录器名称?
问题描述
我正在尝试将日志记录添加到具有多个模块和子模块的 python 应用程序中。一些网站说要在模块中创建子记录器。我看到的优点是子记录器继承了父记录配置,它将为记录输出(处理程序、格式化程序等)提供一致性。
到目前为止,我正在定义__main__
每个类中的类记录器名称并将其与当前类的名称 ( parentName.childName
) 连接以获取模块的类记录器。感觉不对,也不可扩展。我该如何改进这一点,这样我就不必__main__
在每个类中对类记录器名称进行硬编码?这是我的代码的样子:
我运行的 Py 文件:
###app.py
import logging
from SubModule1 import *
class myApplication():
loggerName='myAPI'
def __init__(self, config_item_1=None,config_item_2=None,...config_item_N=None):
self.logger=self.logConfig()
self.logger.info("Starting my Application")
self.object1=mySubClass1(arg1, arg2, ... argM)
def logConfig(self):
fileLogFormat='%(asctime)s - %(levelname)s - %(message)s'
consoleLogFormat='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
# create logger
#logger = logging.getLogger(__name__)
logger = logging.getLogger(self.loggerName)
logger.setLevel(logging.DEBUG)
####CONSOLE HANDLER####
# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
# create formatter
consoleFormatter = logging.Formatter(consoleLogFormat)
# add formatter to ch
ch.setFormatter(consoleFormatter)
# add ch to logger
logger.addHandler(ch)
####FILE HANDLER####
# create file handler and set level to debug
fh = logging.FileHandler('API_Log.txt')
fh.setLevel(logging.DEBUG)
# create formatter
fileFormatter = logging.Formatter(fileLogFormat)
# add formatter to ch
fh.setFormatter(fileFormatter)
# add ch to logger
logger.addHandler(fh)
logger.info('Logging is started!!')
return logger
def connect(self):
self.logger.info("Connecting to API")
self.object1.connect()
if __name__=="__main__":
config={"config_item_1": x,
"config_item_2": y,
...
"config_item_N": z
}
myApp=myApplication(config['config_item_1'],config['config_item_2'],...config['config_item_N'])
myApp.connect()
模块:
###SubModule1.py
import logging
import app
class mySubClass1():
appRootLoggerName='myAPI'
def __init__(self,item1):
self.logger=logging.getLogger(self.appRootLoggerName + '.'+mySubClass1.__name__)
self.logger.debug("mySubClass1 object created - mySubClass1")
self.classObject1=item1
下面的行是困扰我的行。有什么替代方法self.appRootLoggerName + '.'+mySubClass1.__name__)
可以在我的应用程序的模块/类之间共享相同的日志记录配置?
logging.getLogger(self.appRootLoggerName + '.'+mySubClass1.__name__)
解决方案
推荐阅读
- linux - 使用 wget 从 linux 终端下载 NC 格式的气候数据
- unity3d - Unity设置变换父级而不改变玩家的比例
- javascript - 如何在 html 文件之间切换并在它们之间发送数据?
- python - MNIST 数据集输入数组应具有与目标数组相同数量的样本
- mysql - 如何在 Visual Basic 中获取插入到 mysql 数据库中的记录的 ID?
- grep - 获取路径与基本名称模式匹配的文件名
- python - 如何在 Python 3 中从字符串中提取子字符串
- c++ - 更好地编写程序
- python - 按值排序字典python(word2vec)
- apache-kafka - Kafka MirrorMaker2 自动消费者偏移同步