Achim
Achim

Reputation: 15722

Pass keyword arg to log handler in python logging configuration file

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

Answers (3)

ptommasi
ptommasi

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

zezollo
zezollo

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:

'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

davidedb
davidedb

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

Related Questions