사용자 정의 클래스에서 로거를 래핑하는 동안 문제 발생 (Issue while wrapping logger in custom class)


문제 설명

사용자 정의 클래스에서 로거를 래핑하는 동안 문제 발생 (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.

(by soumeng78soumeng78)

참조 문서

  1. Issue while wrapping logger in custom class (CC BY‑SA 2.5/3.0/4.0)

#Python #python-logging






관련 질문

Python - 파일 이름에 특수 문자가 있는 파일의 이름을 바꿀 수 없습니다. (Python - Unable to rename a file with special characters in the file name)

구조화된 배열의 dtype을 변경하면 문자열 데이터가 0이 됩니다. (Changing dtype of structured array zeros out string data)

목록 목록의 효과적인 구현 (Effective implementation of list of lists)

for 루프를 중단하지 않고 if 문을 중지하고 다른 if에 영향을 줍니다. (Stop if statement without breaking for loop and affect other ifs)

기본 숫자를 10 ^ 9 이상으로 늘리면 코드가 작동하지 않습니다. (Code fails to work when i increase the base numbers to anything over 10 ^ 9)

사용자 지정 대화 상자 PyQT5를 닫고 데이터 가져오기 (Close and get data from a custom dialog PyQT5)

Enthought Canopy의 Python: csv 파일 조작 (Python in Enthought Canopy: manipulating csv files)

학생의 이름을 인쇄하려고 하는 것이 잘못된 것은 무엇입니까? (What is wrong with trying to print the name of the student?)

다단계 열 테이블에 부분합 열 추가 (Adding a subtotal column to a multilevel column table)

여러 함수의 변수를 다른 함수로 사용 (Use variables from multiple functions into another function)

리프 텐서의 값을 업데이트하는 적절한 방법은 무엇입니까(예: 경사하강법 업데이트 단계 중) (What's the proper way to update a leaf tensor's values (e.g. during the update step of gradient descent))

Boto3: 조직 단위의 AMI에 시작 권한을 추가하려고 하면 ParamValidationError가 발생합니다. (Boto3: trying to add launch permission to AMI for an organizational unit raises ParamValidationError)







코멘트