문제 설명
사용자 정의 클래스에서 로거를 래핑하는 동안 문제 발생 (Issue while wrapping logger in custom class)
Python을 처음 사용하고 서식 등을 수정하는 데 필요한 변경 사항을 재사용하기 위해 로깅을 통해 래퍼를 만들려고 합니다.
다음과 같은 방식으로 래퍼 클래스를 작성했습니다. ‑
import logging
import sys
from datetime import datetime
class CustomLogger:
"""This is custom logger class"""
_format_spec = f"[%(name)‑24s | %(asctime)s | %(levelname)s ] (%(filename)‑32s : %(lineno)‑4d) ==> %(message)s"
_date_format_spec = f"%Y‑%m‑%d @ %I:%M:%S %p"
def __init__(self, name, level=logging.DEBUG, format_spec=None):
""""""
self.name = name
self.level = level
self.format_spec = format_spec if format_spec else CustomLogger._format_spec
# Complete logging configuration.
self.logger = self.get_logger(self.name, self.level)
def get_file_handler(self, name, level):
"""This is a method to get a file handler"""
today = datetime.now().strftime(format="%Y‑%m‑%d")
file_handler = logging.FileHandler("{}‑{}.log".format(name, today))
file_handler.setLevel(level)
file_handler.setFormatter(logging.Formatter(self.format_spec,
datefmt=CustomLogger._date_format_spec))
return file_handler
def get_stream_handler(self, level):
"""This is a method to get a stream handler"""
stream_handler = logging.StreamHandler(sys.stdout)
stream_handler.setLevel(level)
stream_handler.setFormatter(logging.Formatter(self.format_spec,
datefmt=CustomLogger._date_format_spec))
return stream_handler
def get_logger(self, name, level):
"""This is a method to get a logger"""
logger = logging.getLogger(name)
logger.addHandler(self.get_file_handler(name, level))
# logger.addHandler(self.get_stream_handler(level))
return logger
def info(self, msg):
"""info message logger method"""
self.logger.info(msg)
def error(self, msg):
"""error message logger method"""
self.logger.error(msg)
def debug(self, msg):
"""debug message logger method"""
self.logger.debug(msg)
def warn(self, msg):
"""warning message logger method"""
self.logger.warn(msg)
def critical(self, msg):
"""critical message logger method"""
self.logger.critical(msg)
def exception(self, msg):
"""exception message logger method"""
self.logger.exception(msg)
하지만 내 CustomLogger를 사용하려고 하면 로그 파일에 아무것도 들어가지 않습니다.
def main():
"""This main function"""
logger = CustomLogger(name="debug", level=logging.DEBUG)
logger.info("Called main")
if __name__ == "__main__":
main()
클래스/함수 래퍼 없이 유사한 작업을 수행하면 작동합니다. 내가 잘못 가고 있는지 확실하지 않습니다. 어떤 포인터라도 도움이 될 것입니다.
질문에 대한 추가 업데이트
이것(custom_logger.py)을 패키지로 만들고 실제 애플리케이션(app.py)에서 사용한 후. py) 파일 이름으로 항상 custom_logger.py를 인쇄하지만 app.py는 인쇄하지 않는 것을 확인했습니다.
이 문제를 해결하는 방법은 무엇입니까? CustomLogger
를 다시 작성해도 괜찮습니다.
참조 솔루션
방법 1:
I missed to do setLevel()
for the logger. After doing that, problem is resolved. I also added pid for the file handler file‑name to avoid any future issue with multi‑process env.
Let me know if there's anything I can do better here wrt any other potential issues.