logging.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. __package__ = 'archivebox.misc'
  2. # TODO: merge/dedupe this file with archivebox/logging_util.py
  3. import sys
  4. from typing import Optional, Union, Tuple, List
  5. from collections import defaultdict
  6. from benedict import benedict
  7. from rich.console import Console
  8. # SETUP RICH CONSOLE / TTY detection / COLOR / PROGRESS BARS
  9. CONSOLE = Console()
  10. IS_TTY = CONSOLE.is_interactive
  11. DEFAULT_CLI_COLORS = benedict(
  12. {
  13. "reset": "\033[00;00m",
  14. "lightblue": "\033[01;30m",
  15. "lightyellow": "\033[01;33m",
  16. "lightred": "\033[01;35m",
  17. "red": "\033[01;31m",
  18. "green": "\033[01;32m",
  19. "blue": "\033[01;34m",
  20. "white": "\033[01;37m",
  21. "black": "\033[01;30m",
  22. }
  23. )
  24. ANSI = benedict({k: '' for k in DEFAULT_CLI_COLORS.keys()})
  25. COLOR_DICT = defaultdict(lambda: [(0, 0, 0), (0, 0, 0)], {
  26. '00': [(0, 0, 0), (0, 0, 0)],
  27. '30': [(0, 0, 0), (0, 0, 0)],
  28. '31': [(255, 0, 0), (128, 0, 0)],
  29. '32': [(0, 200, 0), (0, 128, 0)],
  30. '33': [(255, 255, 0), (128, 128, 0)],
  31. '34': [(0, 0, 255), (0, 0, 128)],
  32. '35': [(255, 0, 255), (128, 0, 128)],
  33. '36': [(0, 255, 255), (0, 128, 128)],
  34. '37': [(255, 255, 255), (255, 255, 255)],
  35. })
  36. # Logging Helpers
  37. def stdout(*args, color: Optional[str]=None, prefix: str='', config: Optional[benedict]=None) -> None:
  38. ansi = DEFAULT_CLI_COLORS if (config or {}).get('USE_COLOR') else ANSI
  39. if color:
  40. strs = [ansi[color], ' '.join(str(a) for a in args), ansi['reset'], '\n']
  41. else:
  42. strs = [' '.join(str(a) for a in args), '\n']
  43. sys.stdout.write(prefix + ''.join(strs))
  44. def stderr(*args, color: Optional[str]=None, prefix: str='', config: Optional[benedict]=None) -> None:
  45. ansi = DEFAULT_CLI_COLORS if (config or {}).get('USE_COLOR') else ANSI
  46. if color:
  47. strs = [ansi[color], ' '.join(str(a) for a in args), ansi['reset'], '\n']
  48. else:
  49. strs = [' '.join(str(a) for a in args), '\n']
  50. sys.stderr.write(prefix + ''.join(strs))
  51. def hint(text: Union[Tuple[str, ...], List[str], str], prefix=' ', config: Optional[benedict]=None) -> None:
  52. ansi = DEFAULT_CLI_COLORS if (config or {}).get('USE_COLOR') else ANSI
  53. if isinstance(text, str):
  54. stderr('{}{lightred}Hint:{reset} {}'.format(prefix, text, **ansi))
  55. else:
  56. stderr('{}{lightred}Hint:{reset} {}'.format(prefix, text[0], **ansi))
  57. for line in text[1:]:
  58. stderr('{} {}'.format(prefix, line))