如何在Python中的模块之间共享记录器实例?

如何在Python中的模块之间共享记录器实例?,第1张

概述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 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 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 logginglogger = logging.getLogger('conf_store')

日志配置是全局设计的.

将当前模块名称用作日志记录密钥是有利的;它可以让您梳理出记录的位置消息:

logger = logging.getLogger(__name__)
总结

以上是内存溢出为你收集整理的如何在Python中的模块之间共享记录器实例?全部内容,希望文章能够帮你解决如何在Python中的模块之间共享记录器实例?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1192882.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-03
下一篇 2022-06-03

发表评论

登录后才能评论

评论列表(0条)

保存