Python

logging (screen out and file)

guruzoa 2021. 2. 19. 08:35

파이썬 프로그램 실행시 화면에 나오는 것을 로깅해서 디버깅할 때 이용할 필요가 있다.

이에, 화면에 출력하면서 파일로 저장하는 방법에 대한 고찰임

ref :stackoverflow.com/questions/9321741/printing-to-screen-and-writing-to-a-file-at-the-same-time

import logging

level    = logging.INFO
format   = '  %(message)s'
handlers = [logging.FileHandler('filename.log'), logging.StreamHandler()]

logging.basicConfig(level = level, format = format, handlers = handlers)
logging.info('Hey, this is working!')

print문을 재정의하는 방법

from typing import Callable

def print_logger(
    old_print: Callable, 
    file_name: str,
) -> Callable:
    """Returns a function which calls `old_print` twice, specifying a `file=` on the second call.

    Arguments:
        old_print: The `print` function to call twice.
        file_name: The name to give the log file.
    """
    def log_print(*args, **kwargs):
        old_print(*args, **kwargs)
        with open(file_name, "a") as log_file:
            old_print(*args, file=log_file, **kwargs)
    return log_print

print = print_logger(print, "logs/my_log.log")