You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过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.info calls, 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 with block, the original logging configuration is automatically restored, so no side effects leak into other tests.

内容的提问来源于stack exchange,提问作者guettli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:20:53