Skip to content

Instantly share code, notes, and snippets.

@skasero
Created July 1, 2025 23:30
Show Gist options
  • Save skasero/e1ea02b3bb411beae728bb89f8c8919e to your computer and use it in GitHub Desktop.
Save skasero/e1ea02b3bb411beae728bb89f8c8919e to your computer and use it in GitHub Desktop.
Surpress log messages for `logging` package.
import logging
from typing import Set
# The global set of suppressed strings is used to avoid logging
_suppressed_strings: Set[str] = set()
class SuppressLogMessagesFilter(logging.Filter):
"""Filter that suppresses log records containing any of the target substrings."""
def filter(self, record: logging.LogRecord) -> bool:
msg = record.getMessage()
return all(s not in msg for s in _suppressed_strings)
def suppress_log_messages(event: object) -> None:
"""Globally suppress log messages that contain the given event string.
Parameters
----------
event : object
The object to suppress from log output. It will be stringified and
matched against log messages.
Returns
-------
None
"""
event_str = str(event)
if event_str in _suppressed_strings:
return
_suppressed_strings.add(event_str)
# Attach filter to all existing loggers
for logger_name in logging.root.manager.loggerDict:
logger = logging.getLogger(logger_name)
if not any(isinstance(f, SuppressLogMessagesFilter) for f in logger.filters):
logger.addFilter(SuppressLogMessagesFilter())
# Also attach to root logger
root = logging.getLogger()
if not any(isinstance(f, SuppressLogMessagesFilter) for f in root.filters):
root.addFilter(SuppressLogMessagesFilter())
"""
You can pass any String into suppress_log_messages and if a log message contains that
string, it will not be logged.
Example of using this for Streamlit would be:
```
from logger_suppressor import suppress_log_messages
from streamlit.runtime.scriptrunner import ScriptRunnerEvent
suppress_log_messages(ScriptRunnerEvent.ENQUEUE_FORWARD_MSG)
```
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment