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

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__)
点赞