log.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. # Colored log
  2. import sys
  3. from distutils.log import * # noqa: F403
  4. from distutils.log import Log as old_Log
  5. from distutils.log import _global_log
  6. from numpy.distutils.misc_util import (red_text, default_text, cyan_text,
  7. green_text, is_sequence, is_string)
  8. def _fix_args(args,flag=1):
  9. if is_string(args):
  10. return args.replace('%', '%%')
  11. if flag and is_sequence(args):
  12. return tuple([_fix_args(a, flag=0) for a in args])
  13. return args
  14. class Log(old_Log):
  15. def _log(self, level, msg, args):
  16. if level >= self.threshold:
  17. if args:
  18. msg = msg % _fix_args(args)
  19. if 0:
  20. if msg.startswith('copying ') and msg.find(' -> ') != -1:
  21. return
  22. if msg.startswith('byte-compiling '):
  23. return
  24. print(_global_color_map[level](msg))
  25. sys.stdout.flush()
  26. def good(self, msg, *args):
  27. """
  28. If we log WARN messages, log this message as a 'nice' anti-warn
  29. message.
  30. """
  31. if WARN >= self.threshold:
  32. if args:
  33. print(green_text(msg % _fix_args(args)))
  34. else:
  35. print(green_text(msg))
  36. sys.stdout.flush()
  37. _global_log.__class__ = Log
  38. good = _global_log.good
  39. def set_threshold(level, force=False):
  40. prev_level = _global_log.threshold
  41. if prev_level > DEBUG or force:
  42. # If we're running at DEBUG, don't change the threshold, as there's
  43. # likely a good reason why we're running at this level.
  44. _global_log.threshold = level
  45. if level <= DEBUG:
  46. info('set_threshold: setting threshold to DEBUG level,'
  47. ' it can be changed only with force argument')
  48. else:
  49. info('set_threshold: not changing threshold from DEBUG level'
  50. ' %s to %s' % (prev_level, level))
  51. return prev_level
  52. def get_threshold():
  53. return _global_log.threshold
  54. def set_verbosity(v, force=False):
  55. prev_level = _global_log.threshold
  56. if v < 0:
  57. set_threshold(ERROR, force)
  58. elif v == 0:
  59. set_threshold(WARN, force)
  60. elif v == 1:
  61. set_threshold(INFO, force)
  62. elif v >= 2:
  63. set_threshold(DEBUG, force)
  64. return {FATAL:-2,ERROR:-1,WARN:0,INFO:1,DEBUG:2}.get(prev_level, 1)
  65. _global_color_map = {
  66. DEBUG:cyan_text,
  67. INFO:default_text,
  68. WARN:red_text,
  69. ERROR:red_text,
  70. FATAL:red_text
  71. }
  72. # don't use INFO,.. flags in set_verbosity, these flags are for set_threshold.
  73. set_verbosity(0, force=True)