Reputation: 15722
According to https://docs.python.org/2/library/logging.config.html#configuration-file-format I can specify arguments to the constructor of a logger, by using the args
key. But this seems to work only for positional arguments. I have a handler which needs some keyword arguments. Is there a way to specify those in the config file?
Upvotes: 4
Views: 4302
Reputation: 1252
Using YAML (not .ini), if you use the () special key instead of the class keyword, all the properties at the same level will be passed as arguments to the constructor.
E.g. using an external formatter, this will ignore the log_colors parameter:
formatters:
class:
class: colorlog.ColoredFormatter
log_colors: { DEBUG: 'cyan', INFO: 'green', WARNING: 'yellow', ERROR: 'red', CRITICAL: 'red,bg_white' }
format: '%(log_color)s[%(asctime)s-%(shorter_levelname)s-%(compact_name)s]%(message)s'
datefmt: '%H:%M:%S'
This instead will work:
formatters:
color:
(): colorlog.ColoredFormatter
log_colors: { DEBUG: 'cyan', INFO: 'green', WARNING: 'yellow', ERROR: 'red', CRITICAL: 'red,bg_white' }
format: '%(log_color)s[%(asctime)s-%(shorter_levelname)s-%(compact_name)s]%(message)s'
datefmt: '%H:%M:%S'
Upvotes: 2
Reputation: 5027
Well I don't agree the answer is just no.
You can put your keyword arguments in a row, like in this example with SysLogHandler, what has no positional arguments, only keyword ones:
class logging.handlers.SysLogHandler(address=('localhost', SYSLOG_UDP_PORT), facility=LOG_USER, socktype=socket.SOCK_DGRAM)
[handler_mainHandler]
class=logging.handlers.SysLogHandler
level=INFO
formatter=defaultFormatter
args=('/dev/log','myapp')
Python will take '/dev/log' as address keyword argument and 'myapp' as facility argument. They are handled the order they show up.
Such an example is in the documentation for both python2 and python3:
[handler_hand05]
class=handlers.SysLogHandler
level=ERROR
formatter=form05
args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)
There are some disadvantages though:
it's not very readable
it's limited: if you need to access to an external library, the use of ext://
does not work well. In such a case, I would suggest to turn the old style configuration file into a yaml one, like described in my question/answer here: How to refer to a standard library in a logging configuration file?
'Upgrading' the old-style written config file into a yaml written one allows to use keyword arguments in a better and more explicit way. Note that the documentation, as well for python2 and python3 talks explicitely about keyword arguments:
The callable will be called with the remaining items in the configuration sub-dictionary as keyword arguments.
Upvotes: 2
Reputation: 876
I'm sorry to tell you that the answer is no.
Have a look at https://hg.python.org/cpython/file/2.7/Lib/logging/config.py#l163 for more details.
When in doubt, the source code is always your friend!
Upvotes: 3