Coverage for conflog/__init__.py: 97%
35 statements
« prev ^ index » next coverage.py v7.2.4, created at 2024-01-14 05:52 +0000
« prev ^ index » next coverage.py v7.2.4, created at 2024-01-14 05:52 +0000
1"""
2conflog
3=======
4Python logging setup via environment variables and configuration files.
6This library provides a way to configure logging for Python applications.
7It is intended to be used with configuration files in various formats,
8including JSON, INI, XML, and YAML, along with the ability to overwrite
9a configuration via environment variables.
10"""
12from typing import Union
13import logging
14from .handlers.file_handler import init as init_file_handler
15from .handlers.stream_handler import init as init_stream_handler
16from .config import Config
18class Conflog():
19 """A class for managing Python logging logger and handlers.
20 """
22 def __init__(self, conf_files: Union[None, str, list]=None, conf_dict: Union[None, dict]=None):
23 """Initialise Python logging with configuration from
24 configuration files and configuration dictionary.
25 """
27 if isinstance(conf_files, str):
28 conf_files = [conf_files]
30 self.config = Config(conf_files=conf_files, conf_dict=conf_dict)
31 handlers = self.config.get_handlers()
32 datefmt = self.config.get_datefmt()
33 level = self.config.get_level()
34 self.extras = self.config.get_extras()
36 self.handlers = []
37 if 'stream' in handlers:
38 self.handlers.append(init_stream_handler(self.config))
39 if 'file' in handlers:
40 self.handlers.append(init_file_handler(self.config))
42 logging.basicConfig(
43 datefmt=datefmt,
44 level=level
45 )
47 def get_logger(self, name: str) -> logging.Logger:
48 """Get the logger based on the given name
49 and add the handlers to the logger.
50 """
51 logger = logging.getLogger(name)
52 logger.propagate = False # prevent duplicate logging from parent propagation
53 for handler in self.handlers:
54 logger.addHandler(handler)
56 logger = logging.LoggerAdapter(logger, self.extras)
57 logger.setLevel(self.config.get_level())
59 return logger
61 def close_logger_handlers(self, name: str) -> None:
62 """Close logger handlers
63 and clear the handlers from logger.
64 """
65 logger = logging.getLogger(name)
66 for handler in logger.handlers:
67 handler.close()
68 logger.handlers.clear()
70 def get_config_properties(self) -> dict:
71 """Get the configuration properties dictionary.
72 """
73 return self.config.conf