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.

383 lines
9.5KB

  1. #!/usr/bin/env python
  2. # encoding: utf-8
  3. # Thomas Nagy, 2005-2018 (ita)
  4. """
  5. logging, colors, terminal width and pretty-print
  6. """
  7. import os, re, traceback, sys
  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. """
  22. See :py:class:`waflib.Logs.log_filter`
  23. """
  24. verbose = 0
  25. """
  26. Global verbosity level, see :py:func:`waflib.Logs.debug` and :py:func:`waflib.Logs.error`
  27. """
  28. colors_lst = {
  29. 'USE' : True,
  30. 'BOLD' :'\x1b[01;1m',
  31. 'RED' :'\x1b[01;31m',
  32. 'GREEN' :'\x1b[32m',
  33. 'YELLOW':'\x1b[33m',
  34. 'PINK' :'\x1b[35m',
  35. 'BLUE' :'\x1b[01;34m',
  36. 'CYAN' :'\x1b[36m',
  37. 'GREY' :'\x1b[37m',
  38. 'NORMAL':'\x1b[0m',
  39. 'cursor_on' :'\x1b[?25h',
  40. 'cursor_off' :'\x1b[?25l',
  41. }
  42. indicator = '\r\x1b[K%s%s%s'
  43. try:
  44. unicode
  45. except NameError:
  46. unicode = None
  47. def enable_colors(use):
  48. """
  49. If *1* is given, then the system will perform a few verifications
  50. before enabling colors, such as checking whether the interpreter
  51. is running in a terminal. A value of zero will disable colors,
  52. and a value above *1* will force colors.
  53. :param use: whether to enable colors or not
  54. :type use: integer
  55. """
  56. if use == 1:
  57. if not (sys.stderr.isatty() or sys.stdout.isatty()):
  58. use = 0
  59. if Utils.is_win32 and os.name != 'java':
  60. term = os.environ.get('TERM', '') # has ansiterm
  61. else:
  62. term = os.environ.get('TERM', 'dumb')
  63. if term in ('dumb', 'emacs'):
  64. use = 0
  65. if use >= 1:
  66. os.environ['TERM'] = 'vt100'
  67. colors_lst['USE'] = use
  68. # If console packages are available, replace the dummy function with a real
  69. # implementation
  70. try:
  71. get_term_cols = ansiterm.get_term_cols
  72. except AttributeError:
  73. def get_term_cols():
  74. return 80
  75. get_term_cols.__doc__ = """
  76. Returns the console width in characters.
  77. :return: the number of characters per line
  78. :rtype: int
  79. """
  80. def get_color(cl):
  81. """
  82. Returns the ansi sequence corresponding to the given color name.
  83. An empty string is returned when coloring is globally disabled.
  84. :param cl: color name in capital letters
  85. :type cl: string
  86. """
  87. if colors_lst['USE']:
  88. return colors_lst.get(cl, '')
  89. return ''
  90. class color_dict(object):
  91. """attribute-based color access, eg: colors.PINK"""
  92. def __getattr__(self, a):
  93. return get_color(a)
  94. def __call__(self, a):
  95. return get_color(a)
  96. colors = color_dict()
  97. re_log = re.compile(r'(\w+): (.*)', re.M)
  98. class log_filter(logging.Filter):
  99. """
  100. Waf logs are of the form 'name: message', and can be filtered by 'waf --zones=name'.
  101. For example, the following::
  102. from waflib import Logs
  103. Logs.debug('test: here is a message')
  104. Will be displayed only when executing::
  105. $ waf --zones=test
  106. """
  107. def __init__(self, name=''):
  108. logging.Filter.__init__(self, name)
  109. def filter(self, rec):
  110. """
  111. Filters log records by zone and by logging level
  112. :param rec: log entry
  113. """
  114. rec.zone = rec.module
  115. if rec.levelno >= logging.INFO:
  116. return True
  117. m = re_log.match(rec.msg)
  118. if m:
  119. rec.zone = m.group(1)
  120. rec.msg = m.group(2)
  121. if zones:
  122. return getattr(rec, 'zone', '') in zones or '*' in zones
  123. elif not verbose > 2:
  124. return False
  125. return True
  126. class log_handler(logging.StreamHandler):
  127. """Dispatches messages to stderr/stdout depending on the severity level"""
  128. def emit(self, record):
  129. """
  130. Delegates the functionality to :py:meth:`waflib.Log.log_handler.emit_override`
  131. """
  132. # default implementation
  133. try:
  134. try:
  135. self.stream = record.stream
  136. except AttributeError:
  137. if record.levelno >= logging.WARNING:
  138. record.stream = self.stream = sys.stderr
  139. else:
  140. record.stream = self.stream = sys.stdout
  141. self.emit_override(record)
  142. self.flush()
  143. except (KeyboardInterrupt, SystemExit):
  144. raise
  145. except: # from the python library -_-
  146. self.handleError(record)
  147. def emit_override(self, record, **kw):
  148. """
  149. Writes the log record to the desired stream (stderr/stdout)
  150. """
  151. self.terminator = getattr(record, 'terminator', '\n')
  152. stream = self.stream
  153. if unicode:
  154. # python2
  155. msg = self.formatter.format(record)
  156. fs = '%s' + self.terminator
  157. try:
  158. if (isinstance(msg, unicode) and getattr(stream, 'encoding', None)):
  159. fs = fs.decode(stream.encoding)
  160. try:
  161. stream.write(fs % msg)
  162. except UnicodeEncodeError:
  163. stream.write((fs % msg).encode(stream.encoding))
  164. else:
  165. stream.write(fs % msg)
  166. except UnicodeError:
  167. stream.write((fs % msg).encode('utf-8'))
  168. else:
  169. logging.StreamHandler.emit(self, record)
  170. class formatter(logging.Formatter):
  171. """Simple log formatter which handles colors"""
  172. def __init__(self):
  173. logging.Formatter.__init__(self, LOG_FORMAT, HOUR_FORMAT)
  174. def format(self, rec):
  175. """
  176. Formats records and adds colors as needed. The records do not get
  177. a leading hour format if the logging level is above *INFO*.
  178. """
  179. try:
  180. msg = rec.msg.decode('utf-8')
  181. except Exception:
  182. msg = rec.msg
  183. use = colors_lst['USE']
  184. if (use == 1 and rec.stream.isatty()) or use == 2:
  185. c1 = getattr(rec, 'c1', None)
  186. if c1 is None:
  187. c1 = ''
  188. if rec.levelno >= logging.ERROR:
  189. c1 = colors.RED
  190. elif rec.levelno >= logging.WARNING:
  191. c1 = colors.YELLOW
  192. elif rec.levelno >= logging.INFO:
  193. c1 = colors.GREEN
  194. c2 = getattr(rec, 'c2', colors.NORMAL)
  195. msg = '%s%s%s' % (c1, msg, c2)
  196. else:
  197. # remove single \r that make long lines in text files
  198. # and other terminal commands
  199. msg = re.sub(r'\r(?!\n)|\x1B\[(K|.*?(m|h|l))', '', msg)
  200. if rec.levelno >= logging.INFO:
  201. # the goal of this is to format without the leading "Logs, hour" prefix
  202. if rec.args:
  203. try:
  204. return msg % rec.args
  205. except UnicodeDecodeError:
  206. return msg.encode('utf-8') % rec.args
  207. return msg
  208. rec.msg = msg
  209. rec.c1 = colors.PINK
  210. rec.c2 = colors.NORMAL
  211. return logging.Formatter.format(self, rec)
  212. log = None
  213. """global logger for Logs.debug, Logs.error, etc"""
  214. def debug(*k, **kw):
  215. """
  216. Wraps logging.debug and discards messages if the verbosity level :py:attr:`waflib.Logs.verbose` ≤ 0
  217. """
  218. if verbose:
  219. k = list(k)
  220. k[0] = k[0].replace('\n', ' ')
  221. log.debug(*k, **kw)
  222. def error(*k, **kw):
  223. """
  224. Wrap logging.errors, adds the stack trace when the verbosity level :py:attr:`waflib.Logs.verbose` ≥ 2
  225. """
  226. log.error(*k, **kw)
  227. if verbose > 2:
  228. st = traceback.extract_stack()
  229. if st:
  230. st = st[:-1]
  231. buf = []
  232. for filename, lineno, name, line in st:
  233. buf.append(' File %r, line %d, in %s' % (filename, lineno, name))
  234. if line:
  235. buf.append(' %s' % line.strip())
  236. if buf:
  237. log.error('\n'.join(buf))
  238. def warn(*k, **kw):
  239. """
  240. Wraps logging.warning
  241. """
  242. log.warning(*k, **kw)
  243. def info(*k, **kw):
  244. """
  245. Wraps logging.info
  246. """
  247. log.info(*k, **kw)
  248. def init_log():
  249. """
  250. Initializes the logger :py:attr:`waflib.Logs.log`
  251. """
  252. global log
  253. log = logging.getLogger('waflib')
  254. log.handlers = []
  255. log.filters = []
  256. hdlr = log_handler()
  257. hdlr.setFormatter(formatter())
  258. log.addHandler(hdlr)
  259. log.addFilter(log_filter())
  260. log.setLevel(logging.DEBUG)
  261. def make_logger(path, name):
  262. """
  263. Creates a simple logger, which is often used to redirect the context command output::
  264. from waflib import Logs
  265. bld.logger = Logs.make_logger('test.log', 'build')
  266. bld.check(header_name='sadlib.h', features='cxx cprogram', mandatory=False)
  267. # have the file closed immediately
  268. Logs.free_logger(bld.logger)
  269. # stop logging
  270. bld.logger = None
  271. The method finalize() of the command will try to free the logger, if any
  272. :param path: file name to write the log output to
  273. :type path: string
  274. :param name: logger name (loggers are reused)
  275. :type name: string
  276. """
  277. logger = logging.getLogger(name)
  278. if sys.hexversion > 0x3000000:
  279. encoding = sys.stdout.encoding
  280. else:
  281. encoding = None
  282. hdlr = logging.FileHandler(path, 'w', encoding=encoding)
  283. formatter = logging.Formatter('%(message)s')
  284. hdlr.setFormatter(formatter)
  285. logger.addHandler(hdlr)
  286. logger.setLevel(logging.DEBUG)
  287. return logger
  288. def make_mem_logger(name, to_log, size=8192):
  289. """
  290. Creates a memory logger to avoid writing concurrently to the main logger
  291. """
  292. from logging.handlers import MemoryHandler
  293. logger = logging.getLogger(name)
  294. hdlr = MemoryHandler(size, target=to_log)
  295. formatter = logging.Formatter('%(message)s')
  296. hdlr.setFormatter(formatter)
  297. logger.addHandler(hdlr)
  298. logger.memhandler = hdlr
  299. logger.setLevel(logging.DEBUG)
  300. return logger
  301. def free_logger(logger):
  302. """
  303. Frees the resources held by the loggers created through make_logger or make_mem_logger.
  304. This is used for file cleanup and for handler removal (logger objects are re-used).
  305. """
  306. try:
  307. for x in logger.handlers:
  308. x.close()
  309. logger.removeHandler(x)
  310. except Exception:
  311. pass
  312. def pprint(col, msg, label='', sep='\n'):
  313. """
  314. Prints messages in color immediately on stderr::
  315. from waflib import Logs
  316. Logs.pprint('RED', 'Something bad just happened')
  317. :param col: color name to use in :py:const:`Logs.colors_lst`
  318. :type col: string
  319. :param msg: message to display
  320. :type msg: string or a value that can be printed by %s
  321. :param label: a message to add after the colored output
  322. :type label: string
  323. :param sep: a string to append at the end (line separator)
  324. :type sep: string
  325. """
  326. info('%s%s%s %s', colors(col), msg, colors.NORMAL, label, extra={'terminator':sep})