pythonloggingtqdm

Change logging "print" function to "tqdm.write" so logging doesn't interfere with progress bars


I have a simple question: How do I change the built-in Python logger's print function to tqdm.write such that logging messages do not interfere with tqdm's progress bars?


Solution

  • tqdm now has a built-in contextmanager for redirecting the logger:

    import logging
    from tqdm import trange
    from tqdm.contrib.logging import logging_redirect_tqdm
    
    LOG = logging.getLogger(__name__)
    
    if __name__ == '__main__':
        logging.basicConfig(level=logging.INFO)
        with logging_redirect_tqdm():
            for i in trange(9):
                if i == 4:
                    LOG.info("console logging redirected to `tqdm.write()`")
        # logging restored
    

    Copied from tqdm documentation