How to use the coloredlogs.__init__.FormatStringParser function in coloredlogs

To help you get started, weā€™ve selected a few coloredlogs examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github xolox / python-coloredlogs / coloredlogs / __init__.py View on Github external
# defined by the environment variable $COLOREDLOGS_DATE_FORMAT (or fall
        # back to the default).
        if not formatter_options['datefmt']:
            formatter_options['datefmt'] = os.environ.get('COLOREDLOGS_DATE_FORMAT') or DEFAULT_DATE_FORMAT
        # Python's logging module shows milliseconds by default through special
        # handling in the logging.Formatter.formatTime() method [1]. Because
        # coloredlogs always defines a `datefmt' it bypasses this special
        # handling, which is fine because ever since publishing coloredlogs
        # I've never needed millisecond precision ;-). However there are users
        # of coloredlogs that do want milliseconds to be shown [2] so we
        # provide a shortcut to make it easy.
        #
        # [1] https://stackoverflow.com/questions/6290739/python-logging-use-milliseconds-in-time-format
        # [2] https://github.com/xolox/python-coloredlogs/issues/16
        if kw.get('milliseconds'):
            parser = FormatStringParser(style=style)
            if not (parser.contains_field(formatter_options['fmt'], 'msecs')
                    or '%f' in formatter_options['datefmt']):
                pattern = parser.get_pattern('asctime')
                replacements = {'%': '%(msecs)03d', '{': '{msecs:03}', '$': '${msecs}'}
                formatter_options['fmt'] = pattern.sub(
                    r'\g<0>,' + replacements[style],
                    formatter_options['fmt'],
                )
        # Do we need to make %(hostname) available to the formatter?
        HostNameFilter.install(
            fmt=formatter_options['fmt'],
            handler=handler,
            style=style,
            use_chroot=kw.get('use_chroot', True),
        )
        # Do we need to make %(programname) available to the formatter?
github xolox / python-coloredlogs / coloredlogs / __init__.py View on Github external
def install(cls, handler, fmt, programname=None, style=DEFAULT_FORMAT_STYLE):
        """
        Install the :class:`ProgramNameFilter` (only if needed).

        :param fmt: The log format string to check for ``%(programname)``.
        :param style: One of the characters ``%``, ``{`` or ``$`` (defaults to
                      :data:`DEFAULT_FORMAT_STYLE`).
        :param handler: The logging handler on which to install the filter.
        :param programname: Refer to :func:`__init__()`.

        If `fmt` is given the filter will only be installed if `fmt` uses the
        ``programname`` field. If `fmt` is not given the filter is installed
        unconditionally.
        """
        if fmt:
            parser = FormatStringParser(style=style)
            if not parser.contains_field(fmt, 'programname'):
                return
        handler.addFilter(cls(programname))
github xolox / python-coloredlogs / coloredlogs / __init__.py View on Github external
2. If the group contains multiple formatting directives that
              have styles defined then each formatting directive is styled
              individually and surrounding text isn't styled.

        As an example consider the default log format (:data:`DEFAULT_LOG_FORMAT`)::

         %(asctime)s %(hostname)s %(name)s[%(process)d] %(levelname)s %(message)s

        The default field styles (:data:`DEFAULT_FIELD_STYLES`) define a style for the
        `name` field but not for the `process` field, however because both fields
        are part of the same whitespace delimited token they'll be highlighted
        together in the style defined for the `name` field.
        """
        result = []
        parser = FormatStringParser(style=style)
        for group in parser.get_grouped_pairs(fmt):
            applicable_styles = [self.nn.get(self.field_styles, token.name) for token in group if token.name]
            if sum(map(bool, applicable_styles)) == 1:
                # If exactly one (1) field style is available for the group of
                # tokens then all of the tokens will be styled the same way.
                # This provides a limited form of backwards compatibility with
                # the (intended) behavior of coloredlogs before the release of
                # version 10.
                result.append(ansi_wrap(
                    ''.join(token.text for token in group),
                    **next(s for s in applicable_styles if s)
                ))
            else:
                for token in group:
                    text = token.text
                    if token.name: