다른 모듈에서 사용자 정의 로거 처리 (Handling custom logger across different modules)


문제 설명

다른 모듈에서 사용자 정의 로거 처리 (Handling custom logger across different modules)

custom_log 메소드를 불러오고 불러오기만 하면 다양한 모듈에서 사용할 수 있는 python을 사용하여 내 목적에 맞는 사용자 정의 로거를 생성합니다.

이것은 MyLogger.py 스크립트입니다.

import datetime
import logging
import logging.handlers
import os
import colorlog
from pathlib import Path

class MyLogger(logging.Logger):
    def __init__(self, verbose=1):
        log_dir_path = Path("../logs")
        file_name_format = '{year:04d}{month:02d}{day:02d}‑{hour:02d}{minute:02d}{second:02d}.log'
        file_msg_format = '%(asctime)s %(levelname)‑8s [%(filename)s:%(lineno)d] %(message)s'
        console_msg_format = '%(asctime)s %(levelname)‑8s: %(message)s'

        logger = logging.getLogger()
        logger.setLevel(logging.DEBUG)

        if (verbose == 1):
            max_bytes = 1024 ** 2
            backup_count = 100
            t = datetime.datetime.now()
            file_name = file_name_format.format(year=t.year, month=t.month, day=t.day, hour=t.hour, minute=t.minute,
                                                second=t.second)
            file_name = os.path.join(log_dir_path, file_name)
            file_handler = logging.handlers.RotatingFileHandler(filename=file_name, maxBytes=max_bytes, backupCount=backup_count)
            file_handler.setLevel(logging.DEBUG)
            file_formatter = logging.Formatter(file_msg_format)
            file_handler.setFormatter(file_formatter)
            logger.addHandler(file_handler)

        if (verbose == 1):
            cformat = '%(log_color)s' + console_msg_format
            colors = {'DEBUG': 'green', 'INFO': 'cyan', 'WARNING': 'bold_yellow', 'ERROR': 'bold_red',
                      'CRITICAL': 'bold_purple'}
            date_format = '%Y‑%m‑%d %H:%M:%S'
            formatter = colorlog.ColoredFormatter(cformat, date_format, log_colors=colors)
            stream_handler = logging.StreamHandler()
            stream_handler.setLevel(logging.DEBUG)
            stream_handler.setFormatter(formatter)
            logger.addHandler(stream_handler)

    def custom_log(self, level, msg):
        logging.log(getattr(logging,level),msg)

아래와 같은 디렉토리에 2개의 다른 스크립트가 있습니다. 테스트 시작 시 Test1.py에서 MyLogger()를 초기화하고 다른 모든 스크립트에서 custom_log를 사용할 것으로 예상하기만 하면 됩니다. 초기화 방법이나 가져오기 방법에서 이 작업을 수행하기 위해 여기에서 누락된 것이 있습니다. 이 작업을 수행하는 방법에 대한 지원이 필요합니다.

Test1.py

from MyLogger import MyLogger

class StartTest():
    def __init__(self):
        MyLogger.custom_log('DEBUG','Debug messages are only sent to the logfile.')


if __name__ == '__main__':
    MyLogger()
    StartTest()

Test2.py

6
from MyLogger import MyLogger

class Test():
    def __init__(self):
        MyLogger.custom_log('DEBUG','Debug messages are only sent to the logfile.')

    def TestMethod(self):
        MyLogger.custom_log('INFO','Debug messages are only sent to the logfile.')

참조 솔루션

방법 1:

You can achieve it by creating a logger with a specific name instead of using root logger. logging.log() uses always the root logger. So, you can define a logger with a specific name instead of creating a new Logging channel.

An example which is inline with your need

class MyLogger:
    logger: logging.Logger = None

    @staticmethod
    def configure(verbose=1):
        log_dir_path = Path("../logs")
        file_name_format = '{year:04d}{month:02d}{day:02d}‑{hour:02d}{minute:02d}{second:02d}.log'
        file_msg_format = '%(asctime)s %(levelname)‑8s [%(filename)s:%(lineno)d] %(message)s'
        console_msg_format = '%(asctime)s %(levelname)‑8s: %(message)s'

        logger = logging.getLogger("mylogger")
        logger.setLevel(logging.DEBUG)

        cformat = '%(log_color)s' + console_msg_format
        colors = {'DEBUG': 'green', 'INFO': 'cyan', 'WARNING': 'bold_yellow', 'ERROR': 'bold_red',
                  'CRITICAL': 'bold_purple'}
        date_format = '%Y‑%m‑%d %H:%M:%S'
        formatter = colorlog.ColoredFormatter(cformat, date_format, log_colors=colors)
        stream_handler = logging.StreamHandler()
        stream_handler.setLevel(logging.DEBUG)
        stream_handler.setFormatter(formatter)
        logger.addHandler(stream_handler)
        MyLogger.logger = logger

if __name__ == '__main__':
    MyLogger.configure()
    MyLogger.logger.error("debug message")

Once the MyLogger.configure is called, then you can use the MyLogger.logger.* any where in your app / scripts.

This can be done without a helper class as well. Create a logger configuration file. Configure your custom logger with a different name rather than root, and from your code always call logging.getLogger("name‑of‑logger") to create a logging instance.

(by PARKris)

참조 문서

  1. Handling custom logger across different modules (CC BY‑SA 2.5/3.0/4.0)

#Python #python-logging #python-3.x






관련 질문

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)







코멘트