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.

339 lines
8.2KB

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