markwalker_
markwalker_

Reputation: 12869

Filter a string if it's found in a list

I've created a wrapper for logging in Python & want to ignore certain strings. I believed you could simply do something like if msg in FILTER to match a string in a list of strings.

So I tried this;

FILTER = ["Couldn't eval", "wrapWithType"]

class LegacyLogger(logging.Logger):
    def legacydebug(self, msg, *args, **kwargs):
        """
        Log messages.

        @param msg: Information to log
        @type msg: str
        """
        if not any(msg in s for s in FILTER):    # also tried 'if not msg in FILTER'
            self._log(LEGACY_DEBUG_LVL, msg, '')

    logging.Logger.legacydebug = legacydebug

But this isn't working as my log features lines like 'Couldn't eval Y because of name 'Y' is not defined' so does this look for a total match on the string and not a partial match?

Upvotes: 0

Views: 82

Answers (2)

Halldór Bjarni
Halldór Bjarni

Reputation: 57

You just have to reverse it I think, try:

if any([s in msg for s in FILTER]):

You were trying to match the whole msg to a string in filter, which doesn't give you any matches.

Upvotes: 2

Bartosz Marcinkowski
Bartosz Marcinkowski

Reputation: 6881

I think what you want is if not any(s in msg for s in FILTER):.

Upvotes: 2

Related Questions