Repository URL to install this package:
|
Version:
1.0.16 ▾
|
import logging.config
from configurator.manager import YamlConfigManager
import os
#the default YAML logger path
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
DEFAULT_CONFIG_PATH = os.path.join(CURRENT_DIR, 'defaultConfig.yaml')
#the namespace (key) in the YAML configuration file of the desired logger configuration
LOGGER_NAMESPACE = 'logger'
HANDLERS_NAMESPACE = 'handlers'
FILE_NAME_KEY = 'filename'
class Logger():
"""
Instance that creates a YAML configured logger
"""
def __init__(self, config_path=DEFAULT_CONFIG_PATH, log_file_path=None):
"""
:param self: Logger instance
:param config_path: path to a YAML formatted logging configuration file
:param log_file_path: path to a log file for the Logger
"""
assert (isinstance(config_path,str)),'Config path have to be String!'
#getting the logger desired configurations dictionary
config_mgr = YamlConfigManager(config_path)
self.yaml_config = config_mgr.pyYAML_dict[LOGGER_NAMESPACE]
#if new log file path is specified then configure it for the loggers that write to a file
#and creates the log file directoris if not exist
if log_file_path:
self._configure_new_log_file(log_file_path)
#creating configured logger
logging.config.dictConfig(self.yaml_config)
def _configure_new_log_file(self, log_file_path):
"""
:param self: Logger instance
:param log_file_path: path to a log file for the Logger
Configures the specified log file path as the filename of all the loggers that write to file
And also creates the log file directories if not exist
"""
assert isinstance(log_file_path, str) or log_file_path == None, \
'parameter \'namespace\' should be of type string, not {}'.format(type(log_file_path))
#changing the log file path if the parameter is given
handlers = self.yaml_config[HANDLERS_NAMESPACE]
for handler in handlers:
if FILE_NAME_KEY in handlers[handler]:
handlers[handler][FILE_NAME_KEY] = log_file_path
#creating log directory
log_file_dir = os.path.abspath(os.path.dirname(log_file_path))
if not os.path.exists(log_file_dir):
os.makedirs(log_file_dir)