如何在Python中的模块之间共享记录器实例?
发布时间:2020-12-20 11:29:36 所属栏目:Python 来源:网络整理
导读:lib_xml.py的模块: import conf_storedef hello(): print conf_store.logger conf_store.logger.debug('why') print 'where' conf_store.py的模块: #! /usr/bin/python import os,subprocess,logging,time,shutil,fcntlimport lib_xmldef log(): """ a log
lib_xml.py的模块:
import conf_store def hello(): print conf_store.logger conf_store.logger.debug('why') print 'where' conf_store.py的模块: #! /usr/bin/python import os,subprocess,logging,time,shutil,fcntl import lib_xml def log(): """ a log handle """ import logging.handlers global logger LOG_PATH = "/opt/conf_store.log" logger = logging.getLogger('conf_store') logger.setLevel(logging.DEBUG) ch = logging.handlers.WatchedFileHandler(LOG_PATH) ch.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') ch.setFormatter(formatter) logger.addHandler(ch) if __name__ == "__main__": log() while(True): lib_xml.hello() logger.debug('what') 如何在lib_xml.py和conf_store.py之间共享logger对象? 解决方法
您可以将其留给日志记录模块.
只需导入记录;具有相同键的logging.getLogger()将始终返回相同的对象;以下代码添加到lib_xml会将消息记录到同一记录器: import logging logger = logging.getLogger('conf_store') 日志配置是全局设计的. 将当前模块名称用作日志记录密钥是有利的;它可以让您梳理出记录的位置消息: logger = logging.getLogger(__name__) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |