|
| 1 | + |
| 2 | +import logging |
| 3 | +from sys import stdout, stderr, platform |
| 4 | +from collections import defaultdict |
| 5 | +from colorama import Style as Colo_Style, Fore as Colo_Fore |
| 6 | + |
| 7 | +class LevelDifferentiatingFormatter(logging.Formatter): |
| 8 | + def format(self, record): |
| 9 | + if record.levelno > 30: |
| 10 | + record.msg = '{}{}[ERROR]{}{}: '.format( |
| 11 | + Err_Style.BRIGHT, Err_Fore.RED, Err_Fore.RESET, |
| 12 | + Err_Style.RESET_ALL) + record.msg |
| 13 | + elif record.levelno > 20: |
| 14 | + record.msg = '{}{}[WARNING]{}{}: '.format( |
| 15 | + Err_Style.BRIGHT, Err_Fore.RED, Err_Fore.RESET, |
| 16 | + Err_Style.RESET_ALL) + record.msg |
| 17 | + elif record.levelno > 10: |
| 18 | + record.msg = '{}[INFO]{}: '.format( |
| 19 | + Err_Style.BRIGHT, Err_Style.RESET_ALL) + record.msg |
| 20 | + else: |
| 21 | + record.msg = '{}{}[DEBUG]{}{}: '.format( |
| 22 | + Err_Style.BRIGHT, Err_Fore.LIGHTBLACK_EX, Err_Fore.RESET, |
| 23 | + Err_Style.RESET_ALL) + record.msg |
| 24 | + return super(LevelDifferentiatingFormatter, self).format(record) |
| 25 | + |
| 26 | +logger = logging.getLogger('p4a') |
| 27 | +if not hasattr(logger, 'touched'): # Necessary as importlib reloads |
| 28 | + # this, which would add a second |
| 29 | + # handler and reset the level |
| 30 | + logger.setLevel(logging.INFO) |
| 31 | + logger.touched = True |
| 32 | + ch = logging.StreamHandler(stderr) |
| 33 | + formatter = LevelDifferentiatingFormatter('%(message)s') |
| 34 | + ch.setFormatter(formatter) |
| 35 | + logger.addHandler(ch) |
| 36 | +info = logger.info |
| 37 | +debug = logger.debug |
| 38 | +warning = logger.warning |
| 39 | +error = logger.error |
| 40 | + |
| 41 | +class colorama_shim(object): |
| 42 | + |
| 43 | + def __init__(self): |
| 44 | + self._dict = defaultdict(str) |
| 45 | + |
| 46 | + def __getattr__(self, key): |
| 47 | + return self._dict[key] |
| 48 | + |
| 49 | +Null_Style = Null_Fore = colorama_shim() |
| 50 | + |
| 51 | +if stdout.isatty(): |
| 52 | + Out_Style = Colo_Style |
| 53 | + Out_Fore = Colo_Fore |
| 54 | +else: |
| 55 | + Out_Style = Null_Style |
| 56 | + Out_Fore = Null_Fore |
| 57 | + |
| 58 | +if stderr.isatty(): |
| 59 | + Err_Style = Colo_Style |
| 60 | + Err_Fore = Colo_Fore |
| 61 | +else: |
| 62 | + Err_Style = Null_Style |
| 63 | + Err_Fore = Null_Fore |
0 commit comments