Reputation: 3532
In my python project, I have a custom Log formatter which I'd like to pass a string to at construction, and for it to add that to the message it's logging out:
class MyCustomFormatter(logging.Formatter):
def __init__(self, *args, **kwargs):
super(MyCustomFormatter, self).__init__(*args, **kwargs)
print(f'configuring {args} {kwargs}')
if 'constants' in kwargs:
self.constants = kwargs.get('constants')
I am configuring my logging using the logging.yml configuration provided by python:
version: 1
formatters:
standardFormatter:
class: MyCustomFormatter
constants: "constants"
handlers:
consoleHandler:
class: logging.StreamHandler
level: INFO
formatter: standardFormatter
stream: ext://sys.stdout
root:
level: DEBUG
handlers: [consoleHandler]
I was expecting 'constants' to be passed in the kwargs to MyCustomFormatter.init, however kwargs seems to be empty. How do I configure a value in the logging config and have that passed to my formatter?
Upvotes: 2
Views: 1954
Reputation: 5195
Unknown keys that are found in the logging dict are only passed as kwargs to the constructor for handlers or when using custom instantiation with the special ()
key. So in your case you would need to configure your formatter like this:
formatters:
standardFormatter:
(): importpath.for.MyCustomFormatter
constants: constants
I would recomend though to not use dictConfig
at all and go with fileConfig
, which makes a lot of special cases like this easier.
Upvotes: 3