如何通过Mocking临时调整日志级别,屏蔽INFO级日志输出?
Suppressing
logging.info() in a Method with mock.patch for Testing Got it, let's tackle your need to temporarily silence logging.info() calls inside my_method_which_does_log() using mock.patch for your single-process, single-threaded test scenario. Here are two reliable, clean solutions:
Approach 1: Directly Mock logging.info
This is the simplest method—we replace the logging.info function with a no-op (do-nothing) function within the context manager. Any calls to logging.info inside your method will be ignored entirely:
import mock import logging from your_module import my_method_which_does_log def test_suppress_info_logs(): with mock.patch('logging.info') as mock_info: # Make the mocked info method do nothing mock_info.return_value = None # Call your target method my_method_which_does_log() # Optional: Verify info was called (if you need to test the logging logic itself) # mock_info.assert_called_once_with("Expected log message")
Approach 2: Temporarily Raise the Logger's Level
If you want to keep higher-priority logs (like WARNING or ERROR) visible while suppressing INFO, this approach is more flexible. We'll patch the logger's level to skip INFO and below:
import mock import logging from your_module import my_method_which_does_log def test_suppress_info_keep_high_level_logs(): # Get the logger used in your method (use your custom logger name if needed, e.g., logging.getLogger("my_app")) target_logger = logging.getLogger() # Temporarily set the logger level to WARNING—this filters out INFO and DEBUG logs with mock.patch.object(target_logger, 'level', logging.WARNING): my_method_which_does_log()
Key Notes
- Approach 1 is ideal when you want to completely ignore all
logging.infocalls, regardless of which logger is used. - Approach 2 is better for debugging, as it lets you still see critical logs while suppressing verbose info messages.
- Both methods are safe for single-process, single-threaded tests: once you exit the
withblock, the original logging configuration is automatically restored, so no side effects leak into other tests.
内容的提问来源于stack exchange,提问作者guettli
相关产品推荐
相关产品推荐

