log.py 2.7 KB

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