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를 안하면서 중간 중간 결과물을 볼 수 있어서 좋았다.
728x90
'분석 Python > 구현 및 자료' 카테고리의 다른 글
pycaret 2.3.1) tune_model hyperopt example (0) | 2021.06.20 |
---|---|
numpy에서 dict을 이용해서 값을 바꾸는 방법 (2) | 2021.06.06 |
python3.7 이후) dataclass __post_init__ 간략하게 알아보기 (0) | 2021.04.25 |
[Python] Icecream 패키지를 사용하여 디버깅하기 (0) | 2021.01.16 |
[Python] itertools (0) | 2021.01.01 |