Python全局日志记录 [英] Python global logging

查看:77
本文介绍了Python全局日志记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使Logger全局化,以便可以在我制作的每个模块中使用它?

How do I make a Logger global so that I can use it in every module I make?

在ModuleA中这样的事情:

Something like this in moduleA:

import logging
import moduleB

log = logging.getLogger('')

result = moduleB.goFigure(5)
log.info('Answer was', result)

在ModuleB中使用它:

With this in moduleB:

def goFigure(integer):
    if not isinstance(integer, int):
        log.critical('not an integer')
    else:
        return integer + 1

当前,我将收到一个错误消息,因为moduleB不知道log是什么.我该如何解决?

Currently, I will get an error because moduleB does not know what log is. How do I get around that?

推荐答案

您可以使自己的日志记录模块"实例化记录器,而不是将所有代码导入.认为:

You could make your own logging "module" which instantiates the logger, than have all of your code import that instead. Think:

logger.py:

logger.py:

import logging
log = logging.getLogger('')

codeA.py:

from logger import log
log.info('whatever')

codeB.py:

from logger import log
log.warn('some other thing')

这篇关于Python全局日志记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆