How to disable logging when running tests in Python

Better Stack Team
Updated on August 25, 2023

To disable logging when running tests in Python, you can temporarily adjust the log level or remove the log handlers used during the test execution. This will prevent logs from being displayed or saved during testing. Here are two common approaches to achieve this:

1. Temporarily change the log level during testing

This approach sets the log level to CRITICAL, which disables all logging with levels lower than or equal to CRITICAL. You can adjust the log level to WARNING, ERROR, or other levels based on your requirements.

 
import logging

def disable_logging_during_tests():
    # Store the current log level to restore it later
    original_log_level = logging.getLogger().getEffectiveLevel()

    # Set the log level to a higher level, e.g., WARNING or CRITICAL
    logging.disable(logging.CRITICAL)

    # Run your tests here

    # Restore the original log level after the tests
    logging.disable(original_log_level)

# Call this function before running your tests
disable_logging_during_tests()

2. Temporarily remove the log handlers during testing

This approach removes all existing log handlers from the root logger, effectively disabling any log output during testing. After the tests are completed, the original log handlers are restored.

 
import logging

def disable_logging_during_tests():
    # Store the current log handlers to restore them later
    original_log_handlers = logging.getLogger().handlers[:]

    # Remove all existing log handlers
    for handler in original_log_handlers:
        logging.getLogger().removeHandler(handler)

    # Run your tests here

    # Restore the original log handlers after the tests
    for handler in original_log_handlers:
        logging.getLogger().addHandler(handler)

# Call this function before running your tests
disable_logging_during_tests()

Choose the approach that suits your needs. If you only need to suppress log messages during testing, changing the log level is usually sufficient. However, if you have more complex logging setups or want to ensure that no logs are written or displayed during testing, removing the log handlers might be a better option.

To learn more about logging in Python, visit Better Stack Community.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →