我有这个 pydev 项目,我做这个项目是为了学习如何正确使用记录器
project
..|.src
..|..|.core
..|..|...|__init__.py
..|..|...|classHanger.py
..|..|...|scripts
..|..|.entrypoint.py
..|..|.util.py
..|
..|.cli
..|..|.cliloggertest.py
..|
..|.config
.....|.logger.conf
类机库.py
#!/usr/bin/env python
# --*-- encoding: iso-8859-1 --*--
import logging
class SpeakingClass(object):
def __init__(self):
self.logger = logging.getLogger("%s.%s" % (__name__, "SpeakingClass"))
def speakingMethod(self):
self.logger.info("I'm a method from a SpeakingClass instance")
脚本.py
#!env python
# --*-- encoding: iso-8859-1 --*--
import logging
logger = logging.getLogger("%s.%s" % (__name__, "scripts"))
def anotherRandomMethod():
logger.info("Now I'm talking from core.scripts.anotherRandomMethod")
入口点.py
#!/usr/bin/env python
# --*-- encoding: iso-8859-1 --*--
import logging
from core.classHangar import SpeakingClass
from core.scripts import anotherRandomMethod
logger = logging.getLogger("%s.%s" % (__name__, "entrypoint"))
def randomMethod():
logger.info("Now I'm in the entrypoint.randomMethod")
def methodCalledByCli():
logger.info("Now I'm in the entrypoint.methodCalledByCli")
randomMethod()
anotherRandomMethod()
speaking_object = SpeakingClass()
speaking_object.speakingMethod()
cliloggertest.py
#!env python
# --*-- encoding: iso-8859-1 --*--
import sys
sys.path.insert(0, '../src/')
import os
import logging.config
import util
from entrypoint import methodCalledByCli
def main():
logging.config.fileConfig(os.path.join(util.getProjectPath(), "config/logger.conf"))
logger = logging.getLogger("%s.%s" % (__name__, "cli"))
logger.info("I'm talking from the CLI script")
return methodCalledByCli()
if __name__ == "__main__":
sys.exit(main())
和记录器.conf
[loggers]
keys=root
[handlers]
keys=syserr
[formatters]
keys=basicformatter
[logger_root]
level=DEBUG
handlers=syserr
[handler_syserr]
class=StreamHandler
formatter=basicformatter
args=(sys.stderr,)
[formatter_basicformatter]
format=%(asctime)s %(levelname)-9s%(name)-35s: %(message)s
datefmt=
我通常应该得到:
"I'm talking from the CLI script"
"Now I'm in the entrypoint.methodCalledByCli"
"Now I'm in the entrypoint.randomMethod"
"Now I'm talking from core.scripts.anotherRandomMethod"
"I'm a method from a SpeakingClass instance"
但我得到的是:
"I'm talking from the CLI script"
"I'm a method from a SpeakingClass instance"
我不明白为什么,我请求记录器在 cliloggertest.py 和其他脚本中以完全相同的方式进行记录
ps:我正在启动 cliloggertest.py
EDIT
正如 Mikko Ohtamaa 所说,这是因为导入顺序的原因,cli 正在导入入口点,而入口点正在导入脚本,因此在 CLI 中设置配置之前创建了脚本的记录器和入口点的记录器
以这种方式更改 cliloggertest 可以解决问题(在任何非内部 python 导入之前设置配置:
#!env python
# --*-- encoding: iso-8859-1 --*--
import sys
sys.path.insert(0, '../src/')
import os
import util
import logging.config
logging.config.fileConfig(os.path.join(util.getProjectPath(), "config/logger.conf"))
from entrypoint import methodCalledByCli
def main():
logger = logging.getLogger("cliloggertest")
logger.info("I'm talking from the CLI script")
return methodCalledByCli()
if __name__ == "__main__":
sys.exit(main())