tqdm) print대신에 tqdm을 이용해서 logging 방법

2021. 5. 15. 15:13분석 Python/구현 및 자료

728x90

간혹 먼가 로깅을 하고 싶은 경우에 print를 많이 쓴다. 

하지만 print를 하다 보면, 계속 남기 때문에 메모리를 차지하거나 보기에 좋지가 않다.

그래서 이런 것을 해결할 수 있는 게 보통 tqdm이고 여기서 logging과 tqdm을 접목시켜

tqdm 방법을 이용해서 logging까지 하는 것을 공유한다. 

tqdm logging handler 라는 것을 구현해서 사용하면 되기 때문에 공유한다.

 

tqdm handler

import logging
from tqdm import tqdm

class TqdmLoggingHandler(logging.StreamHandler):
    """Avoid tqdm progress bar interruption by logger's output to console"""
    # see logging.StreamHandler.eval method:
    # https://github.com/python/cpython/blob/d2e2534751fd675c4d5d3adc208bf4fc984da7bf/Lib/logging/__init__.py#L1082-L1091
    # and tqdm.write method:
    # https://github.com/tqdm/tqdm/blob/f86104a1f30c38e6f80bfd8fb16d5fcde1e7749f/tqdm/std.py#L614-L620

    def emit(self, record):
        try:
            msg = self.format(record)
            tqdm.write(msg, end=self.terminator)
        except RecursionError:
            raise
        except Exception:
            self.handleError(record)
import time

log = logging.getLogger(__name__)
log.handlers = []
log.setLevel(logging.INFO)
log.addHandler(TqdmLoggingHandler())

 

예제 코드

 

추가적으로 set_postprefix를 이용해서 로깅되지 않는 부분에 대해서 추가적으로 중간중간 결과를 볼 수 있어서 추가했다.

from time import sleep
pbar = tqdm(range(100))
for epoch in pbar :
    sleep(1)
    if epoch % 10 == 0 :
        log.info(f"check")
    pbar.set_postfix({'logging' : epoch})

 

 

위의 결과처럼 tqdm 중간 중간 결과를 로깅할 수 있다!

handler를 조금 더 수정하면, txt file에도 추가할 수 있는 기능도 같이 할 수 있을 것이다!

 

다른 결과물

이런식으로 print를 안하면서 중간 중간 결과물을 볼 수 있어서 좋았다. 

 

 

https://stackoverflow.com/questions/38543506/change-logging-print-function-to-tqdm-write-so-logging-doesnt-i nterfere-wit

 

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? Thanks!

stackoverflow.com

 

728x90