跨多个模块/功能使用记录器

时间:2014-02-07 10:24:22

标签: python python-2.7 logging

我有以下用于创建记录器的代码:

import logging
import a as a


def main():

    # create logger
    logger = logging.getLogger('cli_logger')
    logger.setLevel(logging.DEBUG)

    #Create file handler
    fh = logging.FileHandler('cli_log.log')
    fh.setLevel(logging.DEBUG)

    # create console handler
    ch = logging.StreamHandler()
    ch.setLevel(logging.INFO)

    # create formatter and add it to the handlers
    formatter = logging.Formatter('\n%(asctime)s - %(module)s - %(funcName)s()\n%(message)s\n')
    fh.setFormatter(formatter)
    ch.setFormatter(formatter)

    # add the handlers to the logger
    logger.addHandler(fh)
    logger.addHandler(ch)

    logger.info("This should print to console and log file!")
    logger.debug("This should print to the log file!")

    #Do module stuff
    a.write_something1()
    a.write_something2()
    ...

if __name__ == '__main__':
    main()

这是否意味着 - 对于模块a中的每个函数,我必须再次获取记录器?

module a
import logging

def write_something1():
    logger = logging.getLogger('cli_logger')

    logger.info('Module A1: Console and Debug Log')
    logger.debug('Module A1: Debug Log')

def write_something2():
    logger = logging.getLogger('cli_logger')

    logger.info('Module A2: Console and Debug Log')
    logger.debug('Module A2: Debug Log')

1 个答案:

答案 0 :(得分:2)

首先,我会避免记录器的“程序内”配置,并将所有配置内容移动到外部文件,如http://docs.python.org/2/howto/logging.html#configuring-logging中所述。

此外,在每个模块中,我都会创建一个特定于该特定模块的模块范围的记录器实例 。因此,您将有可能增加特定模块的详细程度。此外,您不需要在日志消息的开头显示标签。

关于代码重复。实际上它只有一行:

# this is my.library.module
import logging
logger = logging.getLogger("my.library.module")

logger.debug("module loaded")
...