|
| 1 | +import sys |
| 2 | + |
| 3 | +from pathlib import Path |
| 4 | +from loguru import logger, _Logger as Logger |
| 5 | + |
| 6 | + |
| 7 | +class LoggerConfigError(Exception): |
| 8 | + pass |
| 9 | + |
| 10 | + |
| 11 | +class LoggerCustomizer: |
| 12 | + |
| 13 | + @classmethod |
| 14 | + def make_logger(cls, log_path: Path, |
| 15 | + log_filename: str, |
| 16 | + log_level: str, |
| 17 | + log_rotation_interval: str, |
| 18 | + log_retention_interval: str, |
| 19 | + log_format: str) -> Logger: |
| 20 | + """Creates a logger from given configurations |
| 21 | +
|
| 22 | + Args: |
| 23 | + log_path (Path): Path where the log file is located |
| 24 | + log_filename (str): |
| 25 | +
|
| 26 | + log_level (str): The level we want to start logging from |
| 27 | + log_rotation_interval (str): Every how long the logs |
| 28 | + would be rotated |
| 29 | + log_retention_interval (str): Amount of time in words defining |
| 30 | + how long the log will be kept |
| 31 | + log_format (str): The logging format |
| 32 | +
|
| 33 | + Raises: |
| 34 | + LoggerConfigError: Error raised when the configuration is invalid |
| 35 | +
|
| 36 | + Returns: |
| 37 | + Logger: Loguru logger instance |
| 38 | + """ |
| 39 | + try: |
| 40 | + logger = cls.customize_logging( |
| 41 | + file_path=Path(log_path) / Path(log_filename), |
| 42 | + level=log_level, |
| 43 | + retention=log_retention_interval, |
| 44 | + rotation=log_rotation_interval, |
| 45 | + format=log_format |
| 46 | + ) |
| 47 | + except (TypeError, ValueError) as err: |
| 48 | + raise LoggerConfigError( |
| 49 | + f"You have an issue with the logger configuration: {err!r}, " |
| 50 | + "fix it please") |
| 51 | + |
| 52 | + return logger |
| 53 | + |
| 54 | + @classmethod |
| 55 | + def customize_logging(cls, |
| 56 | + file_path: Path, |
| 57 | + level: str, |
| 58 | + rotation: str, |
| 59 | + retention: str, |
| 60 | + format: str |
| 61 | + ) -> Logger: |
| 62 | + """Used to customize the logger instance |
| 63 | +
|
| 64 | + Args: |
| 65 | + file_path (Path): Path where the log file is located |
| 66 | + level (str): The level wanted to start logging from |
| 67 | + rotation (str): Every how long the logs would be |
| 68 | + rotated(creation of new file) |
| 69 | + retention (str): Amount of time in words defining how |
| 70 | + long a log is kept |
| 71 | + format (str): The logging format |
| 72 | +
|
| 73 | + Returns: |
| 74 | + Logger: Instance of a logger mechanism |
| 75 | + """ |
| 76 | + logger.remove() |
| 77 | + logger.add( |
| 78 | + sys.stdout, |
| 79 | + enqueue=True, |
| 80 | + backtrace=True, |
| 81 | + level=level.upper(), |
| 82 | + format=format |
| 83 | + ) |
| 84 | + logger.add( |
| 85 | + str(file_path), |
| 86 | + rotation=rotation, |
| 87 | + retention=retention, |
| 88 | + enqueue=True, |
| 89 | + backtrace=True, |
| 90 | + level=level.upper(), |
| 91 | + format=format |
| 92 | + ) |
| 93 | + |
| 94 | + return logger |
0 commit comments