실버를 위한 코딩/파이썬 연습

[파이썬 연습] 로깅과 어노테이션

forSilver 2024. 8. 14. 02:41
반응형

로깅과 어노테이션

로깅과 어노테이션을 함께 사용하는 방법을 설명드리겠습니다. 로깅은 프로그램의 실행 과정을 추적하고 기록하는 방법입니다. 파이썬의 logging 모듈을 사용하면 다양한 수준의 로그 메시지를 쉽게 기록할 수 있습니다. 이를 함수에 어노테이션으로 추가하여 함수 호출 시마다 로그를 남길 수 있습니다.

로깅 설정

먼저 로깅 설정을 합니다. 로깅 설정은 일반적으로 프로그램의 시작 부분에 위치시킵니다.

import logging

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

데코레이터를 사용한 로깅

로깅을 함수에 추가하려면 데코레이터를 사용합니다. 데코레이터는 함수 호출 전후에 로그 메시지를 기록할 수 있습니다.

from typing import Callable

def log_decorator(func: Callable) -> Callable:
    def wrapper(*args, **kwargs):
        logger.info(f"Function '{func.__name__}' started with args: {args} and kwargs: {kwargs}")
        result = func(*args, **kwargs)
        logger.info(f"Function '{func.__name__}' finished with result: {result}")
        return result
    return wrapper

예제

로깅 데코레이터와 타입 어노테이션을 함께 사용하는 예제를 작성해 보겠습니다.

1. get_even_numbers 함수

from typing import List

@log_decorator
def get_even_numbers(numbers: List[int]) -> List[int]:
    return [num for num in numbers if num % 2 == 0]

# 테스트
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(get_even_numbers(numbers))  # [2, 4, 6, 8, 10]

2. calculate_distance 함수

from typing import Tuple
import math

@log_decorator
def calculate_distance(point1: Tuple[float, float], point2: Tuple[float, float]) -> float:
    return math.sqrt((point2[0] - point1[0])**2 + (point2[1] - point1[1])**2)

# 테스트
point1 = (0.0, 0.0)
point2 = (3.0, 4.0)
print(calculate_distance(point1, point2))  # 5.0

3. get_top_student 함수

from typing import Dict

@log_decorator
def get_top_student(students: Dict[str, int]) -> str:
    return max(students, key=students.get)

# 테스트
students = {"Alice": 85, "Bob": 92, "Charlie": 88}
print(get_top_student(students))  # Bob

종합 코드

모든 내용을 종합한 전체 코드는 다음과 같습니다.

import logging
from typing import List, Tuple, Dict, Callable
import math

# 로깅 설정
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

# 로깅 데코레이터
def log_decorator(func: Callable) -> Callable:
    def wrapper(*args, **kwargs):
        logger.info(f"Function '{func.__name__}' started with args: {args} and kwargs: {kwargs}")
        result = func(*args, **kwargs)
        logger.info(f"Function '{func.__name__}' finished with result: {result}")
        return result
    return wrapper

@log_decorator
def get_even_numbers(numbers: List[int]) -> List[int]:
    return [num for num in numbers if num % 2 == 0]

@log_decorator
def calculate_distance(point1: Tuple[float, float], point2: Tuple[float, float]) -> float:
    return math.sqrt((point2[0] - point1[0])**2 + (point2[1] - point1[1])**2)

@log_decorator
def get_top_student(students: Dict[str, int]) -> str:
    return max(students, key=students.get)

# 테스트
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(get_even_numbers(numbers))  # [2, 4, 6, 8, 10]

point1 = (0.0, 0.0)
point2 = (3.0, 4.0)
print(calculate_distance(point1, point2))  # 5.0

students = {"Alice": 85, "Bob": 92, "Charlie": 88}
print(get_top_student(students))  # Bob

 

이 코드를 실행하면 각 함수 호출 전후에 로깅 메시지가 출력되어 함수의 실행 과정을 추적할 수 있습니다. 이렇게 하면 디버깅이 쉬워지고 코드의 실행 흐름을 쉽게 이해할 수 있습니다.