Python logging.Filter() Examples

The following are 30 code examples of logging.Filter(). 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 also want to check out all available functions/classes of the module logging , or try the search function .
Example #1
Source File: test_logging.py    From sentry-python with BSD 2-Clause "Simplified" License 7 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 #2
Source File: test_logging.py    From Fluid-Designer with 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 #3
Source File: conf.py    From pytest with 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 #4
Source File: setup_logging.py    From sphinxcontrib-versioning with 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 #5
Source File: test_logging.py    From ironpython3 with 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 #6
Source File: leveleditor.py    From GDMC with 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 #7
Source File: runtests.py    From tornado-zh with MIT License 6 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 #8
Source File: cli.py    From linter-pylama with 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 #9
Source File: runtests.py    From tornado-zh with MIT License 6 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
Source File: logging.py    From scylla with Apache License 2.0 5 votes vote down vote up
def filter(self, record):
        # The base Filter class allows only records from a logger (or its
        # children).
        return not super(ExcludeLoggerFilter, self).filter(record) 
Example #11
Source File: loggertochat.py    From hangoutsbot with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, bot):
        self.bot = bot
        logging.Filter.__init__(self) 
Example #12
Source File: util.py    From tws_async with The Unlicense 5 votes vote down vote up
def __init__(self, name, level):
        logging.Filter.__init__(self)
        self.name = name
        self.level = level 
Example #13
Source File: utils.py    From fooltrader with MIT License 5 votes vote down vote up
def init_process_log(file_name, log_dir=None):
    root_logger = logging.getLogger()

    # reset the handlers
    root_logger.handlers = []

    root_logger.setLevel(logging.INFO)

    if log_dir:
        file_name = os.path.join(log_dir, file_name)

    fh = RotatingFileHandler(file_name, maxBytes=524288000, backupCount=10)

    fh.setLevel(logging.INFO)

    ch = logging.StreamHandler()
    ch.setLevel(logging.INFO)

    # create formatter and add it to the handlers
    formatter = logging.Formatter(
        "%(levelname)s  %(threadName)s  %(asctime)s  %(name)s:%(lineno)s  %(funcName)s  %(message)s")
    fh.setFormatter(formatter)
    ch.setFormatter(formatter)

    # filter
    # fh.addFilter(logging.Filter('fooltrader'))

    # add the handlers to the logger
    root_logger.addHandler(fh)
    root_logger.addHandler(ch) 
Example #14
Source File: config.py    From ironpython3 with 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 #15
Source File: config.py    From jawfish with 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 #16
Source File: error.py    From dash-hack with MIT License 5 votes vote down vote up
def __init__(self):
        logging.Filter.__init__(self)
        self.warning_table = {} 
Example #17
Source File: error.py    From dash-hack with MIT License 5 votes vote down vote up
def __init__(self):
        logging.Filter.__init__(self)
        self.warning_table = {} 
Example #18
Source File: error.py    From dash-hack with MIT License 5 votes vote down vote up
def __init__(self):
        logging.Filter.__init__(self)
        self.warning_table = {} 
Example #19
Source File: display.py    From litmus with Apache License 2.0 5 votes vote down vote up
def __init__(self, blacklist):
        self.blacklist = [logging.Filter(name) for name in blacklist] 
Example #20
Source File: config.py    From Imogen with 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 #21
Source File: runtests.py    From pySINDy with 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.info_count = self.warning_count = self.error_count = 0 
Example #22
Source File: test_logging.py    From Fluid-Designer with GNU General Public License v3.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 #23
Source File: test_logging.py    From Fluid-Designer with GNU General Public License v3.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 #24
Source File: test_logging.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_empty_filter(self):
        f = logging.Filter()
        r = logging.makeLogRecord({'name': 'spam.eggs'})
        self.assertTrue(f.filter(r))

#
#   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 #25
Source File: log_util.py    From openbrokerapi with MIT License 5 votes vote down vote up
def basic_config(logger: logging.Logger = logging.root, level=logging.INFO):
    """
    Configures a logger to log <=INFO to stdout and >INFO to stderr

    :param logger: Logger to configure, defaults to logging.root
    :param level: Defaults to INFO
    :return: configured logger (logger from parameters)
    """
    logger.setLevel(level)

    class InfoFilter(logging.Filter):
        def filter(self, rec):
            return rec.levelno in (logging.DEBUG, logging.INFO)

    formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(name)s - %(message)s", "%d/%m/%Y %H:%M:%S")

    std_out_handler = logging.StreamHandler(sys.stdout)
    std_out_handler.setLevel(logging.DEBUG)
    std_out_handler.setFormatter(formatter)
    std_out_handler.addFilter(InfoFilter())

    std_err_handler = logging.StreamHandler()
    std_err_handler.setLevel(logging.WARNING)
    std_err_handler.setFormatter(formatter)

    logger.addHandler(std_out_handler)
    logger.addHandler(std_err_handler)

    return logger 
Example #26
Source File: config.py    From Fluid-Designer with GNU General Public License v3.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 #27
Source File: test_secure.py    From CoAPthon with MIT License 5 votes vote down vote up
def __init__(self, *whitelist):
        super(Filter, self).__init__()
        self.whitelist = [Filter(name) for name in whitelist] 
Example #28
Source File: error.py    From scapy with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self):
        logging.Filter.__init__(self)
        self.warning_table = {} 
Example #29
Source File: error.py    From mptcp-abuse with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self):
        logging.Filter.__init__(self)
        self.warning_table = {} 
Example #30
Source File: test_logging.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_empty_filter(self):
        f = logging.Filter()
        r = logging.makeLogRecord({'name': 'spam.eggs'})
        self.assertTrue(f.filter(r))

#
#   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.
#