Created
July 20, 2020 14:14
-
-
Save theeluwin/ca14e0782f3b79323ff6c00fec0143d6 to your computer and use it in GitHub Desktop.
맨날 쓰는 그 로거
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def get_logger(name, log_dir, use_formatter=True): | |
# 함수를 처음 부르는 경우, static 변수를 추가 | |
if not hasattr(get_logger, '_name2logger'): | |
get_logger._name2logger = {} | |
# 생성한적 없는 로거 객체의 경우, 초기화 | |
if name not in get_logger._name2logger: | |
# 로그 파일 경로 설정 | |
os.makedirs(log_dir, exist_ok=True) | |
log_path = os.path.join(log_dir, f'{name}.log') | |
# 핸들러 생성 | |
handler = logging.FileHandler(log_path) | |
handler.setLevel(logging.INFO) | |
# 포매터 부착 | |
if use_formatter: | |
formatter = logging.Formatter('<%(asctime)s> %(levelname)s: %(message)s') | |
handler.setFormatter(formatter) | |
# 로거 생성 | |
logger = logging.getLogger(name) | |
logger.setLevel(logging.INFO) | |
logger.addHandler(handler) | |
# 로거 등록 | |
get_logger._loggers[name] = logger | |
return get_logger._name2logger[name] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment