[Python] How do I switch to a Python log formatter I have defined in my logging.ini file?

Discussão em 'Python' iniciado por Stack, Maio 16, 2025.

  1. Stack

    Stack Membro Participativo

    This is my logging.ini file:

    [loggers]
    keys=root

    [handlers]
    keys=consoleHandler

    [formatters]
    keys=simpleFormatter,json

    [logger_root]
    level=INFO
    handlers=consoleHandler

    [handler_consoleHandler]
    class=StreamHandler
    formatter=json
    args=(sys.stdout,)

    [formatter_json]
    class=pythonjsonlogger.jsonlogger.JsonFormatter
    format=%(asctime)s %(name)s %(levelname)s %(message)s

    [formatter_simpleFormatter]
    format=%(asctime)s %(name)s - %(levelname)s:%(message)s


    I want to switch the formatter via an environment variable, but this is not working (AttributeError: 'RootLogger' object has no attribute 'setFormatter'):

    import logging.config

    # Load logging config file
    logging_config_file_path = path.join(
    path.dirname(path.abspath(__file__)), "logging.ini"
    )
    logging.config.fileConfig(logging_config_file_path)

    # Override log settings via env vars
    LOGLEVEL = os.environ.get("LOGLEVEL", "INFO").upper()
    LOG_FORMATTER = os.environ.get("LOG_FORMATTER", "simpleFormatter").upper()
    LOGLEVEL_NUMBER = logging.getLevelName(LOGLEVEL)
    LOGLEVEL_DEBUG_NUMBER = 10
    logger = logging.getLogger()
    logger.setLevel(LOGLEVEL)
    # setFormatter seems to want an object
    logger.setFormatter(LOG_FORMATTER


    I have all my settings defined in the ini file. How do I switch a formatter via an environment variable like I currently do for the log level?

    Edit


    Perhaps I must be missing something obvious.

    I tried passing arguments to the config, but it's not working and I can find almost no examples of how to use defaults:

    logging.config.fileConfig(
    logging_config_file_path, defaults={"formatter": "simpleFormatter"}
    )


    In logging.ini

    [handler_consoleHandler]
    class=StreamHandler
    # formatter=simpleFormatter
    formatter='%(formatter)s'


    Throws:

    configparser.InterpolationSyntaxError: bad interpolation variable reference '%(formatter)'

    Continue reading...

Compartilhe esta Página