logging.py 2.6 KB

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