DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Mercurial (c68fe15a81fc)

VCS Links

Line Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
# This Source Code Form is subject to the terms of the Mozilla Public
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.

# This file contains logging functionality for mach. It essentially provides
# support for a structured logging framework built on top of Python's built-in
# support for a structured logging framework built on top of Python's built-in
# logging framework.

from __future__ import absolute_import, unicode_literals

try:
try:
    import blessings
except ImportError:
    blessings = None


import codecs
import json
import logging
import six
import sys
import sys
import time



# stdout and stderr may not necessarily be set up to write Unicode output, so
# reconfigure them if necessary.
def _wrap_stdstream(fh):
    if fh in (sys.stderr, sys.stdout):
        encoding = sys.getdefaultencoding()
        encoding = sys.getdefaultencoding()
        encoding = 'utf-8' if encoding in ('ascii', 'charmap') else encoding
        if six.PY2:
            return codecs.getwriter(encoding)(fh, errors='replace')
        else:
            return codecs.getwriter(encoding)(fh.buffer,
            return codecs.getwriter(encoding)(fh.buffer,
                                              errors='replace')
    else:
        return fh



def format_seconds(total):
    """Format number of seconds to MM:SS.DD form."""

    minutes, seconds = divmod(total, 60)


    return '%2d:%05.2f' % (minutes, seconds)


class ConvertToStructuredFilter(logging.Filter):
    """Filter that converts unstructured records into structured ones."""
    def filter(self, record):
    def filter(self, record):
        if hasattr(record, 'action') and hasattr(record, 'params'):
            return True

        record.action = 'unstructured'
        record.params = {'msg': record.getMessage()}
        record.params = {'msg': record.getMessage()}
        record.msg = '{msg}'

        return True



class StructuredJSONFormatter(logging.Formatter):
    """Log formatter that writes a structured JSON entry."""

    def format(self, record):
        action = getattr(record, 'action', 'UNKNOWN')
        action = getattr(record, 'action', 'UNKNOWN')
        params = getattr(record, 'params', {})

        return json.dumps([record.created, action, params])



class StructuredHumanFormatter(logging.Formatter):
    """Log formatter that writes structured messages for humans.

    It is important that this formatter never be added to a logger that
    It is important that this formatter never be added to a logger that
    produces unstructured/classic log messages. If it is, the call to format()
    could fail because the string could contain things (like JSON) that look
    like formatting character sequences.

    Because of this limitation, format() will fail with a KeyError if an
    Because of this limitation, format() will fail with a KeyError if an
    unstructured record is passed or if the structured message is malformed.
    """
    def __init__(self, start_time, write_interval=False, write_times=True):
    def __init__(self, start_time, write_interval=False, write_times=True):
        self.start_time = start_time
        self.write_interval = write_interval
        self.write_times = write_times
        self.last_time = None


    def format(self, record):
        f = record.msg.format(**record.params)

        if not self.write_times:
            return f

        elapsed = self._time(record)


        return '%s %s' % (format_seconds(elapsed), f)

    def _time(self, record):
        t = record.created - self.start_time


        if self.write_interval and self.last_time is not None:
            t = record.created - self.last_time

        self.last_time = record.created


        return t


class StructuredTerminalFormatter(StructuredHumanFormatter):
    """Log formatter for structured messages writing to a terminal."""
    """Log formatter for structured messages writing to a terminal."""

    def set_terminal(self, terminal):
        self.terminal = terminal
        self._sgr0 = terminal.normal if terminal and blessings else ''


    def format(self, record):
        f = record.msg.format(**record.params)
        f = record.msg.format(**record.params)

        if not self.write_times:
            return f

        t = self.terminal.blue(format_seconds(self._time(record)))
        t = self.terminal.blue(format_seconds(self._time(record)))

        # Some processes (notably Clang) don't reset terminal attributes after
        # printing newlines. This can lead to terminal attributes getting in a
        # wonky state. Work around this by sending the sgr0 sequence after every
        # line to reset all attributes. For programs that rely on the next line
        # line to reset all attributes. For programs that rely on the next line
        # inheriting the same attributes, this will prevent that from happening.
        # But that's better than "corrupting" the terminal.
        return '%s %s%s' % (t, self._colorize(f), self._sgr0)

    def _colorize(self, s):
    def _colorize(self, s):
        if not self.terminal:
            return s


        result = s
        result = s

        reftest = s.startswith('REFTEST ')
        if reftest:
        if reftest:
            s = s[8:]


        if s.startswith('TEST-PASS'):
            result = self.terminal.green(s[0:9]) + s[9:]
        elif s.startswith('TEST-UNEXPECTED'):
            result = self.terminal.red(s[0:20]) + s[20:]
        elif s.startswith('TEST-START'):
        elif s.startswith('TEST-START'):
            result = self.terminal.yellow(s[0:10]) + s[10:]
        elif s.startswith('TEST-INFO'):
            result = self.terminal.yellow(s[0:9]) + s[9:]

        if reftest:
        if reftest:
            result = 'REFTEST ' + result

        return result



class LoggingManager(object):
    """Holds and controls global logging state.

    An application should instantiate one of these and configure it as needed.


    This class provides a mechanism to configure the output of logging data
    both from mach and from the overall logging system (e.g. from other
    modules).
    """

    def __init__(self):
    def __init__(self):
        self.start_time = time.time()

        self.json_handlers = []
        self.terminal_handler = None
        self.terminal_formatter = None
        self.terminal_formatter = None

        self.root_logger = logging.getLogger()
        self.root_logger.setLevel(logging.DEBUG)

        # Installing NullHandler on the root logger ensures that *all* log
        # Installing NullHandler on the root logger ensures that *all* log
        # messages have at least one handler. This prevents Python from
        # complaining about "no handlers could be found for logger XXX."
        self.root_logger.addHandler(logging.NullHandler())


        mach_logger = logging.getLogger('mach')
        mach_logger.setLevel(logging.DEBUG)

        self.structured_filter = ConvertToStructuredFilter()


        self.structured_loggers = [mach_logger]

        self._terminal = None

    @property
    def terminal(self):
        if not self._terminal and blessings:
        if not self._terminal and blessings:
            # Sometimes blessings fails to set up the terminal. In that case,
            # silently fail.
            try:
                terminal = blessings.Terminal(
                    stream=_wrap_stdstream(sys.stdout))
                    stream=_wrap_stdstream(sys.stdout))

                if terminal.is_a_tty:
                    self._terminal = terminal
            except Exception:
                pass
                pass

        return self._terminal

    def add_json_handler(self, fh):
        """Enable JSON logging on the specified file object."""
        """Enable JSON logging on the specified file object."""

        # Configure the consumer of structured messages.
        handler = logging.StreamHandler(stream=fh)
        handler.setFormatter(StructuredJSONFormatter())
        handler.setLevel(logging.DEBUG)
        handler.setLevel(logging.DEBUG)

        # And hook it up.
        for logger in self.structured_loggers:
            logger.addHandler(handler)


        self.json_handlers.append(handler)

    def add_terminal_logging(self, fh=sys.stdout, level=logging.INFO,
                             write_interval=False, write_times=True):
        """Enable logging to the terminal."""
        """Enable logging to the terminal."""

        fh = _wrap_stdstream(fh)
        formatter = StructuredHumanFormatter(self.start_time,
                                             write_interval=write_interval,
                                             write_times=write_times)
                                             write_times=write_times)

        if self.terminal:
            formatter = StructuredTerminalFormatter(self.start_time,
                                                    write_interval=write_interval,
                                                    write_times=write_times)
            formatter.set_terminal(self.terminal)


        handler = logging.StreamHandler(stream=fh)
        handler.setFormatter(formatter)
        handler.setLevel(level)

        for logger in self.structured_loggers:
            logger.addHandler(handler)

        self.terminal_handler = handler
        self.terminal_handler = handler
        self.terminal_formatter = formatter

    def replace_terminal_handler(self, handler):
        """Replace the installed terminal handler.


        Returns the old handler or None if none was configured.
        If the new handler is None, removes any existing handler and disables
        logging to the terminal.
        """
        old = self.terminal_handler
        old = self.terminal_handler

        if old:
            for logger in self.structured_loggers:
                logger.removeHandler(old)


        if handler:
            for logger in self.structured_loggers:
                logger.addHandler(handler)

        self.terminal_handler = handler
        self.terminal_handler = handler

        return old

    def enable_unstructured(self):
    def enable_unstructured(self):
        """Enable logging of unstructured messages."""
        if self.terminal_handler:
            self.terminal_handler.addFilter(self.structured_filter)
            self.root_logger.addHandler(self.terminal_handler)


    def disable_unstructured(self):
        """Disable logging of unstructured messages."""
        if self.terminal_handler:
            self.terminal_handler.removeFilter(self.structured_filter)
            self.root_logger.removeHandler(self.terminal_handler)
            self.root_logger.removeHandler(self.terminal_handler)

    def register_structured_logger(self, logger, terminal=True, json=True):
        """Register a structured logger.

        This needs to be called for all structured loggers that don't chain up
        This needs to be called for all structured loggers that don't chain up
        to the mach logger in order for their output to be captured.
        """
        self.structured_loggers.append(logger)

        if terminal and self.terminal_handler:
        if terminal and self.terminal_handler:
            logger.addHandler(self.terminal_handler)

        if json:
            for handler in self.json_handlers:
                logger.addHandler(handler)

    def enable_all_structured_loggers(self, terminal=True, json=True):
    def enable_all_structured_loggers(self, terminal=True, json=True):
        """Enable logging of all structured messages from all loggers.

        ``terminal`` and ``json`` determine which log handlers to operate
        on. By default, all known handlers are operated on.
        """
        """
        # Remove current handlers from all loggers so we don't double
        # register handlers.
        for logger in self.root_logger.manager.loggerDict.values():
            # Some entries might be logging.PlaceHolder.
            # Some entries might be logging.PlaceHolder.
            if not isinstance(logger, logging.Logger):
                continue

            if terminal:
                logger.removeHandler(self.terminal_handler)
                logger.removeHandler(self.terminal_handler)

            if json:
                for handler in self.json_handlers:
                    logger.removeHandler(handler)


        # Wipe out existing registered structured loggers since they
        # all propagate to root logger.
        self.structured_loggers = []
        self.register_structured_logger(self.root_logger, terminal=terminal,
        self.register_structured_logger(self.root_logger, terminal=terminal,
                                        json=json)