2

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?

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.