Python logging.Filter() Examples

The following are 30 code examples for showing how to use logging.Filter(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module logging , or try the search function .

Example 1
Project: linter-pylama   Author: AtomLinter   File: cli.py    License: MIT License 6 votes vote down vote up
def setup_stream_handlers(conf):
    """Setup logging stream handlers according to the options."""
    class StdoutFilter(logging.Filter):
        def filter(self, record):
            return record.levelno in (logging.DEBUG, logging.INFO)

    log.handlers = []

    stdout_handler = logging.StreamHandler(sys.stdout)
    stdout_handler.setLevel(logging.WARNING)
    stdout_handler.addFilter(StdoutFilter())
    if conf.debug:
        stdout_handler.setLevel(logging.DEBUG)
    elif conf.verbose:
        stdout_handler.setLevel(logging.INFO)
    else:
        stdout_handler.setLevel(logging.WARNING)
    log.addHandler(stdout_handler)

    stderr_handler = logging.StreamHandler(sys.stderr)
    msg_format = "%(levelname)s: %(message)s"
    stderr_handler.setFormatter(logging.Formatter(fmt=msg_format))
    stderr_handler.setLevel(logging.WARNING)
    log.addHandler(stderr_handler) 
Example 2
Project: sentry-python   Author: getsentry   File: test_logging.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_logging_filters(sentry_init, capture_events):
    sentry_init(integrations=[LoggingIntegration()], default_integrations=False)
    events = capture_events()

    should_log = False

    class MyFilter(logging.Filter):
        def filter(self, record):
            return should_log

    logger.addFilter(MyFilter())
    logger.error("hi")

    assert not events

    should_log = True
    logger.error("hi")

    (event,) = events
    assert event["logentry"]["message"] == "hi" 
Example 3
Project: sphinxcontrib-versioning   Author: sphinx-contrib   File: setup_logging.py    License: MIT License 6 votes vote down vote up
def setup_logging(verbose=0, colors=False, name=None):
    """Configure console logging. Info and below go to stdout, others go to stderr.

    :param int verbose: Verbosity level. > 0 print debug statements. > 1 passed to sphinx-build.
    :param bool colors: Print color text in non-verbose mode.
    :param str name: Which logger name to set handlers to. Used for testing.
    """
    root_logger = logging.getLogger(name)
    root_logger.setLevel(logging.DEBUG if verbose > 0 else logging.INFO)
    formatter = ColorFormatter(verbose > 0, colors)
    if colors:
        colorclass.Windows.enable()

    handler_stdout = logging.StreamHandler(sys.stdout)
    handler_stdout.setFormatter(formatter)
    handler_stdout.setLevel(logging.DEBUG)
    handler_stdout.addFilter(type('', (logging.Filter,), {'filter': staticmethod(lambda r: r.levelno <= logging.INFO)}))
    root_logger.addHandler(handler_stdout)

    handler_stderr = logging.StreamHandler(sys.stderr)
    handler_stderr.setFormatter(formatter)
    handler_stderr.setLevel(logging.WARNING)
    root_logger.addHandler(handler_stderr) 
Example 4
Project: pytest   Author: pytest-dev   File: conf.py    License: MIT License 6 votes vote down vote up
def configure_logging(app: "sphinx.application.Sphinx") -> None:
    """Configure Sphinx's WarningHandler to handle (expected) missing include."""
    import sphinx.util.logging
    import logging

    class WarnLogFilter(logging.Filter):
        def filter(self, record: logging.LogRecord) -> bool:
            """Ignore warnings about missing include with "only" directive.

            Ref: https://github.com/sphinx-doc/sphinx/issues/2150."""
            if (
                record.msg.startswith('Problems with "include" directive path:')
                and "_changelog_towncrier_draft.rst" in record.msg
            ):
                return False
            return True

    logger = logging.getLogger(sphinx.util.logging.NAMESPACE)
    warn_handler = [x for x in logger.handlers if x.level == logging.WARNING]
    assert len(warn_handler) == 1, warn_handler
    warn_handler[0].filters.insert(0, WarnLogFilter()) 
Example 5
Project: Fluid-Designer   Author: Microvellum   File: test_logging.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_filter(self):
        # Only messages satisfying the specified criteria pass through the
        #  filter.
        filter_ = logging.Filter("spam.eggs")
        handler = self.root_logger.handlers[0]
        try:
            handler.addFilter(filter_)
            spam = logging.getLogger("spam")
            spam_eggs = logging.getLogger("spam.eggs")
            spam_eggs_fish = logging.getLogger("spam.eggs.fish")
            spam_bakedbeans = logging.getLogger("spam.bakedbeans")

            spam.info(self.next_message())
            spam_eggs.info(self.next_message())  # Good.
            spam_eggs_fish.info(self.next_message())  # Good.
            spam_bakedbeans.info(self.next_message())

            self.assert_log_lines([
                ('spam.eggs', 'INFO', '2'),
                ('spam.eggs.fish', 'INFO', '3'),
            ])
        finally:
            handler.removeFilter(filter_) 
Example 6
Project: ironpython3   Author: IronLanguages   File: test_logging.py    License: Apache License 2.0 6 votes vote down vote up
def test_filter(self):
        # Only messages satisfying the specified criteria pass through the
        #  filter.
        filter_ = logging.Filter("spam.eggs")
        handler = self.root_logger.handlers[0]
        try:
            handler.addFilter(filter_)
            spam = logging.getLogger("spam")
            spam_eggs = logging.getLogger("spam.eggs")
            spam_eggs_fish = logging.getLogger("spam.eggs.fish")
            spam_bakedbeans = logging.getLogger("spam.bakedbeans")

            spam.info(self.next_message())
            spam_eggs.info(self.next_message())  # Good.
            spam_eggs_fish.info(self.next_message())  # Good.
            spam_bakedbeans.info(self.next_message())

            self.assert_log_lines([
                ('spam.eggs', 'INFO', '2'),
                ('spam.eggs.fish', 'INFO', '3'),
            ])
        finally:
            handler.removeFilter(filter_) 
Example 7
Project: GDMC   Author: mcgreentn   File: leveleditor.py    License: ISC License 6 votes vote down vote up
def _resize_selection_box(self, new_box):
        import inspect # Let's get our hands dirty
        stack = inspect.stack()
        filename = os.path.basename(stack[1][1])
        old_box = self.selectionTool.selectionBox()
        msg = """
        Filter "{0}" wants to resize the selection box
        Origin: {1} -> {2}
        Size: {3} -> {4}
        Do you want to resize the Selection Box?""".format(
                   filename, 
                   (old_box.origin[0], old_box.origin[1], old_box.origin[2]), 
                   (new_box.origin[0], new_box.origin[1], new_box.origin[2]), 
                   (old_box.size[0], old_box.size[1], old_box.size[2]), 
                   (new_box.size[0], new_box.size[1], new_box.size[2])
                   )
        result = ask(msg, ["Yes", "No"])
        if result == "Yes":
            self.selectionTool.setSelection(new_box)
            return new_box
        else:
            return False 
Example 8
Project: jawfish   Author: war-and-code   File: config.py    License: MIT License 5 votes vote down vote up
def configure_filter(self, config):
        """Configure a filter from a dictionary."""
        if '()' in config:
            result = self.configure_custom(config)
        else:
            name = config.get('name', '')
            result = logging.Filter(name)
        return result 
Example 9
Project: tornado-zh   Author: tao12345666333   File: runtests.py    License: MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        # Can't use super() because logging.Filter is an old-style class in py26
        logging.Filter.__init__(self, *args, **kwargs)
        self.warning_count = self.error_count = 0 
Example 10
Project: tornado-zh   Author: tao12345666333   File: runtests.py    License: MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        # Can't use super() because logging.Filter is an old-style class in py26
        logging.Filter.__init__(self, *args, **kwargs)
        self.warning_count = self.error_count = 0 
Example 11
Project: BiblioPixel   Author: ManiacalLabs   File: log.py    License: MIT License 5 votes vote down vote up
def _new_custom_logger(name='BiblioPixel',
                       fmt='%(levelname)s - %(module)s - %(message)s'):
    logger = logging.getLogger(name)
    formatter = logging.Formatter(fmt=fmt)

    def add_handler(level, outfile):
        class Filter(logging.Filter):
            def filter(self, rec):
                return rec.levelno == level

        h = logging.StreamHandler(outfile)
        h.setLevel(level)
        h.addFilter(Filter())
        h.setFormatter(formatter)
        logger.addHandler(h)

    if not logger.handlers:
        logger.setLevel(INFO)
        add_handler(FRAME, sys.stdout)
        add_handler(DEBUG, sys.stdout)
        add_handler(INFO, sys.stdout)
        add_handler(WARNING, sys.stderr)
        add_handler(ERROR, sys.stderr)

    else:  # pragma: no cover
        pass

    return logger 
Example 12
Project: rainmachine-developer-resources   Author: sprinkler   File: rmLogging.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
            logging.Filter.__init__(self)
            self.modulesLevel = {} 
Example 13
Project: rainmachine-developer-resources   Author: sprinkler   File: rmLogging.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
            logging.Filter.__init__(self)
            self.modulesLevel = {} 
Example 14
Project: meddle   Author: glmcdona   File: config.py    License: MIT License 5 votes vote down vote up
def configure_filter(self, config):
        """Configure a filter from a dictionary."""
        if '()' in config:
            result = self.configure_custom(config)
        else:
            name = config.get('name', '')
            result = logging.Filter(name)
        return result 
Example 15
Project: ironpython2   Author: IronLanguages   File: config.py    License: Apache License 2.0 5 votes vote down vote up
def configure_filter(self, config):
        """Configure a filter from a dictionary."""
        if '()' in config:
            result = self.configure_custom(config)
        else:
            name = config.get('name', '')
            result = logging.Filter(name)
        return result 
Example 16
Project: ironpython2   Author: IronLanguages   File: test_logging.py    License: Apache License 2.0 5 votes vote down vote up
def test_filter(self):
        # Only messages satisfying the specified criteria pass through the
        #  filter.
        filter_ = logging.Filter("spam.eggs")
        handler = self.root_logger.handlers[0]
        try:
            handler.addFilter(filter_)
            spam = logging.getLogger("spam")
            spam_eggs = logging.getLogger("spam.eggs")
            spam_eggs_fish = logging.getLogger("spam.eggs.fish")
            spam_bakedbeans = logging.getLogger("spam.bakedbeans")

            spam.info(self.next_message())
            spam_eggs.info(self.next_message())  # Good.
            spam_eggs_fish.info(self.next_message())  # Good.
            spam_bakedbeans.info(self.next_message())

            self.assert_log_lines([
                ('spam.eggs', 'INFO', '2'),
                ('spam.eggs.fish', 'INFO', '3'),
            ])
        finally:
            handler.removeFilter(filter_)


#
#   First, we define our levels. There can be as many as you want - the only
#     limitations are that they should be integers, the lowest should be > 0 and
#   larger values mean less information being logged. If you need specific
#   level values which do not fit into these limitations, you can use a
#   mapping dictionary to convert between your application levels and the
#   logging system.
# 
Example 17
Project: ironpython2   Author: IronLanguages   File: test_logging.py    License: Apache License 2.0 5 votes vote down vote up
def test_logger_filter(self):
        # Filter at logger level.
        self.root_logger.setLevel(VERBOSE)
        # Levels >= 'Verbose' are good.
        self.log_at_all_levels(self.root_logger)
        self.assert_log_lines([
            ('Verbose', '5'),
            ('Sociable', '6'),
            ('Effusive', '7'),
            ('Terse', '8'),
            ('Taciturn', '9'),
            ('Silent', '10'),
        ]) 
Example 18
Project: ironpython2   Author: IronLanguages   File: test_logging.py    License: Apache License 2.0 5 votes vote down vote up
def test_handler_filter(self):
        # Filter at handler level.
        self.root_logger.handlers[0].setLevel(SOCIABLE)
        try:
            # Levels >= 'Sociable' are good.
            self.log_at_all_levels(self.root_logger)
            self.assert_log_lines([
                ('Sociable', '6'),
                ('Effusive', '7'),
                ('Terse', '8'),
                ('Taciturn', '9'),
                ('Silent', '10'),
            ])
        finally:
            self.root_logger.handlers[0].setLevel(logging.NOTSET) 
Example 19
Project: premiumizer   Author: piejanssens   File: premiumizer.py    License: MIT License 5 votes vote down vote up
def __init__(self, *errorfilter):
        self.errorfilter = [logging.Filter(name) for name in errorfilter] 
Example 20
Project: CyberScan   Author: medbenali   File: error.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        logging.Filter.__init__(self)
        self.warning_table = {} 
Example 21
Project: BinderFilter   Author: dxwu   File: config.py    License: MIT License 5 votes vote down vote up
def configure_filter(self, config):
        """Configure a filter from a dictionary."""
        if '()' in config:
            result = self.configure_custom(config)
        else:
            name = config.get('name', '')
            result = logging.Filter(name)
        return result 
Example 22
Project: BinderFilter   Author: dxwu   File: test_logging.py    License: MIT License 5 votes vote down vote up
def test_filter(self):
        # Only messages satisfying the specified criteria pass through the
        #  filter.
        filter_ = logging.Filter("spam.eggs")
        handler = self.root_logger.handlers[0]
        try:
            handler.addFilter(filter_)
            spam = logging.getLogger("spam")
            spam_eggs = logging.getLogger("spam.eggs")
            spam_eggs_fish = logging.getLogger("spam.eggs.fish")
            spam_bakedbeans = logging.getLogger("spam.bakedbeans")

            spam.info(self.next_message())
            spam_eggs.info(self.next_message())  # Good.
            spam_eggs_fish.info(self.next_message())  # Good.
            spam_bakedbeans.info(self.next_message())

            self.assert_log_lines([
                ('spam.eggs', 'INFO', '2'),
                ('spam.eggs.fish', 'INFO', '3'),
            ])
        finally:
            handler.removeFilter(filter_)


#
#   First, we define our levels. There can be as many as you want - the only
#     limitations are that they should be integers, the lowest should be > 0 and
#   larger values mean less information being logged. If you need specific
#   level values which do not fit into these limitations, you can use a
#   mapping dictionary to convert between your application levels and the
#   logging system.
# 
Example 23
Project: BinderFilter   Author: dxwu   File: test_logging.py    License: MIT License 5 votes vote down vote up
def test_logger_filter(self):
        # Filter at logger level.
        self.root_logger.setLevel(VERBOSE)
        # Levels >= 'Verbose' are good.
        self.log_at_all_levels(self.root_logger)
        self.assert_log_lines([
            ('Verbose', '5'),
            ('Sociable', '6'),
            ('Effusive', '7'),
            ('Terse', '8'),
            ('Taciturn', '9'),
            ('Silent', '10'),
        ]) 
Example 24
Project: BinderFilter   Author: dxwu   File: test_logging.py    License: MIT License 5 votes vote down vote up
def test_handler_filter(self):
        # Filter at handler level.
        self.root_logger.handlers[0].setLevel(SOCIABLE)
        try:
            # Levels >= 'Sociable' are good.
            self.log_at_all_levels(self.root_logger)
            self.assert_log_lines([
                ('Sociable', '6'),
                ('Effusive', '7'),
                ('Terse', '8'),
                ('Taciturn', '9'),
                ('Silent', '10'),
            ])
        finally:
            self.root_logger.handlers[0].setLevel(logging.NOTSET) 
Example 25
Project: Computable   Author: ktraunmueller   File: config.py    License: MIT License 5 votes vote down vote up
def configure_filter(self, config):
        """Configure a filter from a dictionary."""
        if '()' in config:
            result = self.configure_custom(config)
        else:
            name = config.get('name', '')
            result = logging.Filter(name)
        return result 
Example 26
Project: oss-ftp   Author: aliyun   File: config.py    License: MIT License 5 votes vote down vote up
def configure_filter(self, config):
        """Configure a filter from a dictionary."""
        if '()' in config:
            result = self.configure_custom(config)
        else:
            name = config.get('name', '')
            result = logging.Filter(name)
        return result 
Example 27
Project: oss-ftp   Author: aliyun   File: test_logging.py    License: MIT License 5 votes vote down vote up
def test_filter(self):
        # Only messages satisfying the specified criteria pass through the
        #  filter.
        filter_ = logging.Filter("spam.eggs")
        handler = self.root_logger.handlers[0]
        try:
            handler.addFilter(filter_)
            spam = logging.getLogger("spam")
            spam_eggs = logging.getLogger("spam.eggs")
            spam_eggs_fish = logging.getLogger("spam.eggs.fish")
            spam_bakedbeans = logging.getLogger("spam.bakedbeans")

            spam.info(self.next_message())
            spam_eggs.info(self.next_message())  # Good.
            spam_eggs_fish.info(self.next_message())  # Good.
            spam_bakedbeans.info(self.next_message())

            self.assert_log_lines([
                ('spam.eggs', 'INFO', '2'),
                ('spam.eggs.fish', 'INFO', '3'),
            ])
        finally:
            handler.removeFilter(filter_)


#
#   First, we define our levels. There can be as many as you want - the only
#     limitations are that they should be integers, the lowest should be > 0 and
#   larger values mean less information being logged. If you need specific
#   level values which do not fit into these limitations, you can use a
#   mapping dictionary to convert between your application levels and the
#   logging system.
# 
Example 28
Project: oss-ftp   Author: aliyun   File: test_logging.py    License: MIT License 5 votes vote down vote up
def test_logger_filter(self):
        # Filter at logger level.
        self.root_logger.setLevel(VERBOSE)
        # Levels >= 'Verbose' are good.
        self.log_at_all_levels(self.root_logger)
        self.assert_log_lines([
            ('Verbose', '5'),
            ('Sociable', '6'),
            ('Effusive', '7'),
            ('Terse', '8'),
            ('Taciturn', '9'),
            ('Silent', '10'),
        ]) 
Example 29
Project: oss-ftp   Author: aliyun   File: test_logging.py    License: MIT License 5 votes vote down vote up
def test_handler_filter(self):
        # Filter at handler level.
        self.root_logger.handlers[0].setLevel(SOCIABLE)
        try:
            # Levels >= 'Sociable' are good.
            self.log_at_all_levels(self.root_logger)
            self.assert_log_lines([
                ('Sociable', '6'),
                ('Effusive', '7'),
                ('Terse', '8'),
                ('Taciturn', '9'),
                ('Silent', '10'),
            ])
        finally:
            self.root_logger.handlers[0].setLevel(logging.NOTSET) 
Example 30
Project: pget   Author: halilozercan   File: log.py    License: Apache License 2.0 5 votes vote down vote up
def setup_logging(enabled=True, level=logging.DEBUG):
    global _root_handler
    if _root_handler is not None and _root_handler in logging.root.handler:
        logging.root.removeHandler(_root_handler)
    logging.root.setLevel(logging.NOTSET)
    _root_handler = logging.StreamHandler() if enabled else logging.NullHandler()
    _root_handler.addFilter(logging.Filter("pget"))
    _root_handler.setLevel(level)

    logging.root.addHandler(_root_handler)