[关闭]
@chyoo1991 2015-09-13T12:02:57.000000Z 字数 995 阅读 1606

logging in python

logging


logging的使用方法已经基本了解。但有一些不太明白的地方,记录和总结在这儿。

disable_existing_logger

首先,如果在模块水平定义logger:

  1. # filename : test.py
  2. import logging
  3. logger = logging.getLogger(__name__)
  4. def foo():
  5. logger.info("test!")

然后在其他模块中导入:

  1. # filename testlog.py
  2. import logging
  3. import logging.config
  4. import test
  5. logging.config.fileConfig('log.ini')
  6. 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.

一个取巧的办法是:

  1. # filename test.py
  2. import logging
  3. def foo():
  4. logger = loging.getLogger(__name__)
  5. logger.info('test')
  6. class foo(object):
  7. def __init__(self):
  8. self._logger = logging.getLogger(__name__)
  9. def test(self):
  10. self._logger.info('test')

但 python 2.7之后,为logging.config.fileConfiglogging.config.dictConfig添加了disable_existing_loggers参数。当这个参数的值为false的时候,是可以在模块中取得logger的。挺好。具体可参阅此处

上面这篇文章中还提到了如何使用jsonyaml文件进行配置。如果有此种需求,可以尝试使用。

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注