ets-labs/python-dependency-injector

How can I use the enumeration in the configuration files to build an object?

Opened this issue · 0 comments

Hi guys, there is a problem, I do not know how to implement this in the context of DI.
Idea:
I want to make it so that I can conveniently list the handlers for the standard library "logging" in the config and assemble them in the container.
I want to install something like in YML:

logger_service: ['console','file']

The standard logging package implies that I have to create two handlers with this configuration. A handler for the console, and for the file. Or not what if logger_service empty

I don't understand how I can make an if and select a handler for my logger?
my current code looks like this and it works, but I do not know how to add a handler creation setting based on what is specified in the configuration

import logging
import sys
from dependency_injector import containers, providers

from src.kernel.logger.services_filename import ServicesFilename
from src.kernel.support_services.support_config_path import SupportConfigPath as Path


class ContainerLogger(containers.DeclarativeContainer):
    config = providers.Configuration(yaml_files=[Path.get_path('core.yml')])
    log_filename = providers.Factory(ServicesFilename.get_path, config.logger_filename)

    console_handler = providers.Factory(logging.StreamHandler)
    file_handler = providers.Factory(logging.FileHandler, log_filename)
    
    # logger.addHandler(console_handler)
    # logger.addHandler(file_handler)
    
    logger_level = providers.Factory(config.logger_level, config.logger_level)
    logging_config = providers.Factory(logging.basicConfig, format=config.logger_format, datefmt=config.date_format,
                                       level=logger_level)
    
    logging = providers.Resource(
        logging_config,
        stream=sys.stdout,
    )

tell me at least an idea how can I create handlers based on the config?