|
| 1 | +import logging |
| 2 | +from pathlib import Path |
| 3 | +from os import mkdir |
| 4 | +from os.path import exists |
| 5 | + |
| 6 | +from rich.logging import RichHandler |
| 7 | + |
| 8 | + |
| 9 | +class Logger: |
| 10 | + """Custom logger.""" |
| 11 | + |
| 12 | + def __init__(self, filename: str = "sayu") -> None: |
| 13 | + """ |
| 14 | + Args: |
| 15 | + filename -- filename to use. |
| 16 | + """ |
| 17 | + |
| 18 | + logging.basicConfig( |
| 19 | + format="%(message)s", |
| 20 | + level=logging.INFO, |
| 21 | + datefmt="[%X]", |
| 22 | + handlers=[ |
| 23 | + RichHandler( |
| 24 | + show_time=False, |
| 25 | + show_path=False |
| 26 | + ) |
| 27 | + ] |
| 28 | + ) |
| 29 | + |
| 30 | + self.log: logging.Logger = logging.getLogger("rich") |
| 31 | + |
| 32 | + BASE_PATH: Path = Path.home()/".sayu" |
| 33 | + if not exists(BASE_PATH): |
| 34 | + try: |
| 35 | + mkdir(BASE_PATH) |
| 36 | + except (PermissionError, OSError, IOError) as Err: |
| 37 | + self.logger( |
| 38 | + "E", f"Cannot create directory: {Err}, aborting ..." |
| 39 | + ) |
| 40 | + |
| 41 | + file_log: logging.FileHandler = logging.FileHandler( |
| 42 | + filename=f"{BASE_PATH}/{filename}.log" |
| 43 | + ) |
| 44 | + |
| 45 | + file_log.setLevel(logging.INFO) |
| 46 | + file_log.setFormatter( |
| 47 | + logging.Formatter("%(levelname)s %(message)s") |
| 48 | + ) |
| 49 | + self.log.addHandler(file_log) |
| 50 | + |
| 51 | + def logger(self, exception_: str, message: str) -> None: |
| 52 | + """Log the proccesses using passed message and exception_ variable. |
| 53 | +
|
| 54 | + Args: |
| 55 | + exception_ -- determines what type of log level to use |
| 56 | + message -- message to be logged. |
| 57 | + """ |
| 58 | + |
| 59 | + match exception_: |
| 60 | + case "E": # for major error |
| 61 | + self.log.critical("%s" % (message)) |
| 62 | + case "e": |
| 63 | + self.log.error("%s" % (message)) |
| 64 | + case "I": # to print information in the terminal |
| 65 | + self.log.info("%s" % (message)) |
0 commit comments