how to set FileHandler based on logger name using dictConfig python

Viewed 18

CONTEXT

I'm trying to configure my loggers using dictConfig.

.

THE PROBLEM

I have a lot of loggers and I'm struggling to proper add a file handler to each one of them based on the logger's name (which in turn is based on the file name).

.

WHAT I'VE DONE SO FAR

The way shown below works, but isn't viable to implement on a lot of loggers

This is my config dictionary so far: (i removed many loggers and other configurations that aren't related to the problem for simplicity)

{
    'version': 1,
    'formatters': { 
        'precise': {
            'format': '%(asctime)s : %(filename)s : %(funcName)s : %(levelname)s : %(message)s'
        },
    },

    'handlers': { 
        'to_file_spam': { 
            'class': 'logging.FileHandler',
            'filename': 'logs\\spam.log',
            'level': 'DEBUG',
            'formatter': 'precise'
        },
        'to_file_main': {
            'class': 'logging.FileHandler',
            'filename': 'logs\\__main__.log',
            'level': 'DEBUG',
            'formatter': 'precise'
        },
        'to_file_otherlogger': {
            'class': 'logging.FileHandler',
            'filename': 'logs\\otherlogger.log',
            'level': 'DEBUG',
            'formatter': 'precise'
    },

    'loggers': {
        '__main__': {  # if __name__ == "__main__": ...
            'handlers': ['to_file_main']
        },

        'otherlogger': {
            'handlers': ['to_file_otherlogger']
        }
    },
    
    'root': {
        'level': 'DEBUG',
        'handlers': ['to_file_spam']
    }
}

.

I already tried to configure the FileHandler on the actual .py file, among the getLogger function. Like this:

log = logging.getLogger(__name__)
log.addHandler(logging.FileHandler(__name__))

But this way i lose the "formatter", "level" and other options. I could add them manually, but them the dictConfig starts to lose its value.

It would be great performe something like using the special variable "__name__" on the dict, but it doesn't work

...
'to_file_spam': { 
                'class': 'logging.FileHandler',
                'filename': 'logs\\__name__.log',
                'level': 'DEBUG',
                'formatter': 'precise'
            }
...

.

THE FINAL QUESTION

How can i dynamically add a fileHandler filename to each logger based on their name? (referably using a dictConfig)

0 Answers
Related