Can I have logging.ini file without root logger?

a 夏天 提交于 2020-12-29 06:38:28

问题


Here is how my logging.ini file looks like:

[loggers]
keys=teja

[handlers]
keys=fileHandler

[formatters]
keys=simpleFormatter

[logger_teja]
level=DEBUG
handlers=fileHandler
qualname=tejaLogger

[handler_fileHandler]
class=logging.FileHandler
level=DEBUG
formatter=simpleFormatter
args=("error.log", "w")

[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s

I am getting the follwing error:

File "test.py", line 22, in <module>
    logging.config.fileConfig('logging.ini')
  File "/usr/lib/python2.7/logging/config.py", line 79, in fileConfig
    _install_loggers(cp, handlers, disable_existing_loggers)
  File "/usr/lib/python2.7/logging/config.py", line 183, in _install_loggers
    llist.remove("root")
ValueError: list.remove(x): x not in list

Please help me to figure the problem. Or Please explain me "Why there is always a need to include root logger at all?"


回答1:


If you use the source, you'll see that you must configure a root logger:

# configure the root first
llist = cp["loggers"]["keys"]
llist = llist.split(",")
llist = list(map(lambda x: x.strip(), llist))
llist.remove("root")
section = cp["logger_root"]
root = logging.root
log = root

(where cp is the configparser that loads the .ini file you passed in)

The only reason I can think of is that explicit is better than implicit, so it forces you to declare exactly what you want to do with the root logger, in case you thought it would do some magic. Though I don't thinkg that's a particularly good reason. It was probably just the way someone thought to do it at the time. If you do some further reading:

The fileConfig() API is older than the dictConfig() API and does not provide functionality to cover certain aspects of logging [... N]ote that future enhancements to configuration functionality will be added to dictConfig(), so it’s worth considering transitioning to this newer API when it’s convenient to do so.

And if you consider the dictConfig docs, it appears that you don't have to provide a root logger.

So it appears that you are required to specify a root handler, with no really good reason besides backwards compatibility. If you want to get around that, you'll have to either specify your settings in a Python file or import a JSON file and use the dictConfig method.




回答2:


Just in case it happens to someone else, check that you have commas separating all the logger entries, as you may be missing one, having both fields' names merged.



来源:https://stackoverflow.com/questions/28737858/can-i-have-logging-ini-file-without-root-logger

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!