Config¶
YAMLConfig¶
YAMLConfig
class can be used for loading YAML files with custom tags. This class adds a custom envvar tag to native YAML parser which is used to evaluate environment variables. Supports one or more environment variables in the form of ${VARNAME}
or ${VARNAME:DEFAULT}
within a string. If no default value is specified, empty string is used. Default values can only be treated as plain strings.
Example Usage¶
An example YAML configuration file with environment variables:
version: 1
formatters:
simple:
format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
handlers:
console:
class: logging.StreamHandler
formatter: simple
stream: ext://sys.stdout
file_handler:
class: logging.FileHandler
filename: ${LOGGING_ROOT:.}/${LOG_FILENAME}
formatter: simple
loggers:
test_logger:
level: DEBUG
handlers:
- file_handler
propagate: no
root:
level: NOTSET
handlers:
- console
Load the file with YAMLConfig and start logging:
import logging
from logging_.config import YAMLConfig
with open("logging.yaml", "r") as config_file:
YAMLConfig(config_file.read(), silent=True)
# alternatively, you can use
# YAMLConfig.from_file("logging.yaml", silent=True)
logger = logging.getLogger("test_logger")
logger.debug("This is a debug log")
logger.info("This is an info log")
logger.warning("This is an warning log")
logger.error("This is an error log")
logger.critical("This is a critical log")
Optional Params¶
An explicit silent=True
flag must be set to suppress any file or parsing related exceptions to be thrown.
Regex Matchers¶
Regex used for parsing environment variables: r"\${([^}^{]+)}"
. Allowed patterns: ${VARNAME}
, ${VARNAME:DEFAULT}
, ${VARNAME:}
.
Module Members¶
- class logging_.config.yaml_config.YAMLConfig(config_yaml: str, **kwargs: Any)¶
Bases:
object
YAMLConfig class for loading YAML configurations with custom tagging and transformation rules.
This class adds a custom envvar tag to native YAML parser which is used to evaluate environment variables. Supports one or more environment variables in the form of
${VARNAME}
or${VARNAME:DEFAULT}
within a string. If no default value is specified, empty string is used. Default values can only be treated as plain strings. Inspired by several examples from programcreek:https://www.programcreek.com/python/example/11269/yaml.add_constructor
Example configuration:
# logging.yaml version: 1 formatters: simple: format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s' handlers: file_handler: class: logging.FileHandler filename: ${LOGGING_ROOT:.}/${LOG_FILENAME:test_logger.log} formatter: simple
- __init__(config_yaml: str, **kwargs: Any)¶
Instantiates an YAMLConfig object from configuation string.
Registers implicit resolver for custom tag envvar and adds constructor for the tag. Loads logging config from parsed dictionary using dictConfig.
- Parameters
config_yaml – Configuration YAML string.
**kwargs – Optional arguments:
silent (bool)
: If True, silently ignore YAML errors.
- Raises
ParserError – if config_yaml isn’t a valid YAML string, ignored if
silent=True
.ValueError – if required fields are missing in YAML string, ignored if
silent=True
.TypeError – if empty YAML string is provided, ignored if
silent=True
.
- classmethod from_file(filename: str, **kwargs: Any)¶
Creates an instance from YAML configuration file.
- Parameters
filename – Configuration file path.
**kwargs – Optional arguments:
silent (bool)
: If True, silently ignore file errors.
- Returns
An YAMLConfig instance.
- Raises
FileNotFoundError – if filename is not a valid file path, ignored if
silent=True
.PermissionError – if there is no read permission, ignored if
silent=True
.
- __module__ = 'logging_.config.yaml_config'¶