python / cpython

The Python programming language
https://www.python.org
Other
62.78k stars 30.08k forks source link

Add a new `env://` value converter for logging configuration #124955

Open edgarrmondragon opened 3 days ago

edgarrmondragon commented 3 days ago

Feature or enhancement

Proposal:

It would be nice if Python logging config processed environment variables in a similar way cfg:// and ext:// are at the moment. For example:

import logging
import logging.config

config = {
    "version": 1,
    "disable_existing_loggers": False,
    "formatters": {
        "simple": {
            "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
        }
    },
    "handlers": {
        "console": {
            "class": "logging.FileHandler",
            "level": "DEBUG",
            "formatter": "simple",
            "filename": "env://LOG_FILE",  # <---- this!
        }
    },
    "root": {
        "level": "DEBUG",
        "handlers": ["console"],
    },
}

logging.config.dictConfig(config)
logger = logging.getLogger(__name__)
logger.info("Hello, world!")

Something like this can already be implemented by users if they subclass logging.config.DictConfigurator:

import os
from logging.config import DictConfigurator

class DictConfiguratorWithEnv(DictConfigurator):
    value_converters = {
        "env": "env_convert",
        **DictConfigurator.value_converters,
    }

    def env_convert(self, value):
        return os.environ[value]

However, it'd be nice if Python had built-in support and it might be useful for configuring things like host and port for socket handlers.

I think this is a minor change if accepted, but folks might have thoughts about why this could be a bad idea.

Has this already been discussed elsewhere?

This is a minor feature, which does not need previous discussion elsewhere

Links to previous discussion of this feature:

No response

ericvsmith commented 3 days ago

Feature requests should be discussed at https://discuss.python.org/c/ideas/6 before opening an issue here.