@chyoo1991
2015-09-13T12:02:57.000000Z
字数 995
阅读 1606
logging
logging的使用方法已经基本了解。但有一些不太明白的地方,记录和总结在这儿。
disable_existing_logger
首先,如果在模块水平定义logger:
# filename : test.py
import logging
logger = logging.getLogger(__name__)
def foo():
logger.info("test!")
然后在其他模块中导入:
# filename testlog.py
import logging
import logging.config
import test
logging.config.fileConfig('log.ini')
test.foo()
此时执行testlog.py文件,如果log.ini
里面配置了相应的输出,则不会输出。原因如下:
Because you create the logger at module level, you then import the module before you load the logging configuration from a file. The logging.fileConfig and logging.dictConfig disables existing loggers by default. So, those setting in file will not be applied to your logger.
一个取巧的办法是:
# filename test.py
import logging
def foo():
logger = loging.getLogger(__name__)
logger.info('test')
class foo(object):
def __init__(self):
self._logger = logging.getLogger(__name__)
def test(self):
self._logger.info('test')
但 python 2.7之后,为logging.config.fileConfig
和logging.config.dictConfig
添加了disable_existing_loggers
参数。当这个参数的值为false
的时候,是可以在模块中取得logger的。挺好。具体可参阅此处。
上面这篇文章中还提到了如何使用json
和yaml
文件进行配置。如果有此种需求,可以尝试使用。