jack2 codebase
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

340 lines
8.3KB

  1. #!/usr/bin/env python
  2. # encoding: utf-8
  3. # Thomas Nagy, 2005-2010 (ita)
  4. """
  5. logging, colors, terminal width and pretty-print
  6. """
  7. import os, re, traceback, sys, types
  8. from waflib import Utils, ansiterm
  9. if not os.environ.get('NOSYNC', False):
  10. # synchronized output is nearly mandatory to prevent garbled output
  11. if sys.stdout.isatty() and id(sys.stdout) == id(sys.__stdout__):
  12. sys.stdout = ansiterm.AnsiTerm(sys.stdout)
  13. if sys.stderr.isatty() and id(sys.stderr) == id(sys.__stderr__):
  14. sys.stderr = ansiterm.AnsiTerm(sys.stderr)
  15. # import the logging module after since it holds a reference on sys.stderr
  16. # in case someone uses the root logger
  17. import logging
  18. LOG_FORMAT = os.environ.get('WAF_LOG_FORMAT', '%(asctime)s %(c1)s%(zone)s%(c2)s %(message)s')
  19. HOUR_FORMAT = os.environ.get('WAF_HOUR_FORMAT', '%H:%M:%S')
  20. zones = ''
  21. verbose = 0
  22. colors_lst = {
  23. 'USE' : True,
  24. 'BOLD' :'\x1b[01;1m',
  25. 'RED' :'\x1b[01;31m',
  26. 'GREEN' :'\x1b[32m',
  27. 'YELLOW':'\x1b[33m',
  28. 'PINK' :'\x1b[35m',
  29. 'BLUE' :'\x1b[01;34m',
  30. 'CYAN' :'\x1b[36m',
  31. 'GREY' :'\x1b[37m',
  32. 'NORMAL':'\x1b[0m',
  33. 'cursor_on' :'\x1b[?25h',
  34. 'cursor_off' :'\x1b[?25l',
  35. }
  36. indicator = '\r\x1b[K%s%s%s'
  37. def enable_colors(use):
  38. if use == 1:
  39. if not (sys.stderr.isatty() or sys.stdout.isatty()):
  40. use = 0
  41. if Utils.is_win32 and os.name != 'java':
  42. term = os.environ.get('TERM', '') # has ansiterm
  43. else:
  44. term = os.environ.get('TERM', 'dumb')
  45. if term in ('dumb', 'emacs'):
  46. use = 0
  47. if use >= 1:
  48. os.environ['TERM'] = 'vt100'
  49. colors_lst['USE'] = use
  50. # If console packages are available, replace the dummy function with a real
  51. # implementation
  52. try:
  53. get_term_cols = ansiterm.get_term_cols
  54. except AttributeError:
  55. def get_term_cols():
  56. return 80
  57. get_term_cols.__doc__ = """
  58. Get the console width in characters.
  59. :return: the number of characters per line
  60. :rtype: int
  61. """
  62. def get_color(cl):
  63. if not colors_lst['USE']: return ''
  64. return colors_lst.get(cl, '')
  65. class color_dict(object):
  66. """attribute-based color access, eg: colors.PINK"""
  67. def __getattr__(self, a):
  68. return get_color(a)
  69. def __call__(self, a):
  70. return get_color(a)
  71. colors = color_dict()
  72. re_log = re.compile(r'(\w+): (.*)', re.M)
  73. class log_filter(logging.Filter):
  74. """
  75. The waf logs are of the form 'name: message', and can be filtered by 'waf --zones=name'.
  76. For example, the following::
  77. from waflib import Logs
  78. Logs.debug('test: here is a message')
  79. Will be displayed only when executing::
  80. $ waf --zones=test
  81. """
  82. def __init__(self, name=None):
  83. pass
  84. def filter(self, rec):
  85. """
  86. filter a record, adding the colors automatically
  87. * error: red
  88. * warning: yellow
  89. :param rec: message to record
  90. """
  91. rec.zone = rec.module
  92. if rec.levelno >= logging.INFO:
  93. return True
  94. m = re_log.match(rec.msg)
  95. if m:
  96. rec.zone = m.group(1)
  97. rec.msg = m.group(2)
  98. if zones:
  99. return getattr(rec, 'zone', '') in zones or '*' in zones
  100. elif not verbose > 2:
  101. return False
  102. return True
  103. class log_handler(logging.StreamHandler):
  104. """Dispatches messages to stderr/stdout depending on the severity level"""
  105. def emit(self, record):
  106. # default implementation
  107. try:
  108. try:
  109. self.stream = record.stream
  110. except AttributeError:
  111. if record.levelno >= logging.WARNING:
  112. record.stream = self.stream = sys.stderr
  113. else:
  114. record.stream = self.stream = sys.stdout
  115. self.emit_override(record)
  116. self.flush()
  117. except (KeyboardInterrupt, SystemExit):
  118. raise
  119. except: # from the python library -_-
  120. self.handleError(record)
  121. def emit_override(self, record, **kw):
  122. self.terminator = getattr(record, 'terminator', '\n')
  123. stream = self.stream
  124. if hasattr(types, "UnicodeType"):
  125. # python2
  126. msg = self.formatter.format(record)
  127. fs = '%s' + self.terminator
  128. try:
  129. if (isinstance(msg, unicode) and getattr(stream, 'encoding', None)):
  130. fs = fs.decode(stream.encoding)
  131. try:
  132. stream.write(fs % msg)
  133. except UnicodeEncodeError:
  134. stream.write((fs % msg).encode(stream.encoding))
  135. else:
  136. stream.write(fs % msg)
  137. except UnicodeError:
  138. stream.write((fs % msg).encode("UTF-8"))
  139. else:
  140. logging.StreamHandler.emit(self, record)
  141. class formatter(logging.Formatter):
  142. """Simple log formatter which handles colors"""
  143. def __init__(self):
  144. logging.Formatter.__init__(self, LOG_FORMAT, HOUR_FORMAT)
  145. def format(self, rec):
  146. """Messages in warning, error or info mode are displayed in color by default"""
  147. try:
  148. msg = rec.msg.decode('utf-8')
  149. except Exception:
  150. msg = rec.msg
  151. use = colors_lst['USE']
  152. if (use == 1 and rec.stream.isatty()) or use == 2:
  153. c1 = getattr(rec, 'c1', None)
  154. if c1 is None:
  155. c1 = ''
  156. if rec.levelno >= logging.ERROR:
  157. c1 = colors.RED
  158. elif rec.levelno >= logging.WARNING:
  159. c1 = colors.YELLOW
  160. elif rec.levelno >= logging.INFO:
  161. c1 = colors.GREEN
  162. c2 = getattr(rec, 'c2', colors.NORMAL)
  163. msg = '%s%s%s' % (c1, msg, c2)
  164. else:
  165. msg = msg.replace('\r', '\n')
  166. msg = re.sub(r'\x1B\[(K|.*?(m|h|l))', '', msg)
  167. if rec.levelno >= logging.INFO: # ??
  168. return msg
  169. rec.msg = msg
  170. rec.c1 = colors.PINK
  171. rec.c2 = colors.NORMAL
  172. return logging.Formatter.format(self, rec)
  173. log = None
  174. """global logger for Logs.debug, Logs.error, etc"""
  175. def debug(*k, **kw):
  176. """
  177. Wrap logging.debug, the output is filtered for performance reasons
  178. """
  179. if verbose:
  180. k = list(k)
  181. k[0] = k[0].replace('\n', ' ')
  182. global log
  183. log.debug(*k, **kw)
  184. def error(*k, **kw):
  185. """
  186. Wrap logging.errors, display the origin of the message when '-vv' is set
  187. """
  188. global log
  189. log.error(*k, **kw)
  190. if verbose > 2:
  191. st = traceback.extract_stack()
  192. if st:
  193. st = st[:-1]
  194. buf = []
  195. for filename, lineno, name, line in st:
  196. buf.append(' File "%s", line %d, in %s' % (filename, lineno, name))
  197. if line:
  198. buf.append(' %s' % line.strip())
  199. if buf: log.error("\n".join(buf))
  200. def warn(*k, **kw):
  201. """
  202. Wrap logging.warn
  203. """
  204. global log
  205. log.warn(*k, **kw)
  206. def info(*k, **kw):
  207. """
  208. Wrap logging.info
  209. """
  210. global log
  211. log.info(*k, **kw)
  212. def init_log():
  213. """
  214. Initialize the loggers globally
  215. """
  216. global log
  217. log = logging.getLogger('waflib')
  218. log.handlers = []
  219. log.filters = []
  220. hdlr = log_handler()
  221. hdlr.setFormatter(formatter())
  222. log.addHandler(hdlr)
  223. log.addFilter(log_filter())
  224. log.setLevel(logging.DEBUG)
  225. def make_logger(path, name):
  226. """
  227. Create a simple logger, which is often used to redirect the context command output::
  228. from waflib import Logs
  229. bld.logger = Logs.make_logger('test.log', 'build')
  230. bld.check(header_name='sadlib.h', features='cxx cprogram', mandatory=False)
  231. # have the file closed immediately
  232. Logs.free_logger(bld.logger)
  233. # stop logging
  234. bld.logger = None
  235. The method finalize() of the command will try to free the logger, if any
  236. :param path: file name to write the log output to
  237. :type path: string
  238. :param name: logger name (loggers are reused)
  239. :type name: string
  240. """
  241. logger = logging.getLogger(name)
  242. hdlr = logging.FileHandler(path, 'w')
  243. formatter = logging.Formatter('%(message)s')
  244. hdlr.setFormatter(formatter)
  245. logger.addHandler(hdlr)
  246. logger.setLevel(logging.DEBUG)
  247. return logger
  248. def make_mem_logger(name, to_log, size=8192):
  249. """
  250. Create a memory logger to avoid writing concurrently to the main logger
  251. """
  252. from logging.handlers import MemoryHandler
  253. logger = logging.getLogger(name)
  254. hdlr = MemoryHandler(size, target=to_log)
  255. formatter = logging.Formatter('%(message)s')
  256. hdlr.setFormatter(formatter)
  257. logger.addHandler(hdlr)
  258. logger.memhandler = hdlr
  259. logger.setLevel(logging.DEBUG)
  260. return logger
  261. def free_logger(logger):
  262. """
  263. Free the resources held by the loggers created through make_logger or make_mem_logger.
  264. This is used for file cleanup and for handler removal (logger objects are re-used).
  265. """
  266. try:
  267. for x in logger.handlers:
  268. x.close()
  269. logger.removeHandler(x)
  270. except Exception as e:
  271. pass
  272. def pprint(col, msg, label='', sep='\n'):
  273. """
  274. Print messages in color immediately on stderr::
  275. from waflib import Logs
  276. Logs.pprint('RED', 'Something bad just happened')
  277. :param col: color name to use in :py:const:`Logs.colors_lst`
  278. :type col: string
  279. :param msg: message to display
  280. :type msg: string or a value that can be printed by %s
  281. :param label: a message to add after the colored output
  282. :type label: string
  283. :param sep: a string to append at the end (line separator)
  284. :type sep: string
  285. """
  286. info("%s%s%s %s" % (colors(col), msg, colors.NORMAL, label), extra={'terminator':sep})