log.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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 get_threshold():
  58. return _global_log.threshold
  59. def set_verbosity(v, force=False):
  60. prev_level = _global_log.threshold
  61. if v < 0:
  62. set_threshold(ERROR, force)
  63. elif v == 0:
  64. set_threshold(WARN, force)
  65. elif v == 1:
  66. set_threshold(INFO, force)
  67. elif v >= 2:
  68. set_threshold(DEBUG, force)
  69. return {FATAL:-2,ERROR:-1,WARN:0,INFO:1,DEBUG:2}.get(prev_level, 1)
  70. _global_color_map = {
  71. DEBUG:cyan_text,
  72. INFO:default_text,
  73. WARN:red_text,
  74. ERROR:red_text,
  75. FATAL:red_text
  76. }
  77. # don't use INFO,.. flags in set_verbosity, these flags are for set_threshold.
  78. set_verbosity(0, force=True)