파이썬으로 Azure Functions 로깅 및 모니터링

Azure Functions는 서버리스 컴퓨팅 플랫폼으로, 코드를 실행하기 위한 서버 관리에 대한 부담을 덜어줍니다. 파이썬을 사용하여 Azure Functions를 개발하고 실행할 수 있으며, 이 글에서는 Azure Functions에서의 로깅과 모니터링에 대해 알아보겠습니다.

Logging

로깅은 애플리케이션에서 발생하는 이벤트와 정보를 기록하는 중요한 요소입니다. Azure Functions는 자체 로그 기능을 제공하며, 다음과 같은 방법으로 파이썬으로 로그를 기록할 수 있습니다.

import logging

def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info("This is an informational log")
    logging.warning("This is a warning log")
    logging.error("This is an error log")

위 코드에서는 파이썬의 내장 logging 모듈을 사용하여 로그를 기록합니다. logging.info()는 정보성 로그를, logging.warning()은 경고 로그를, logging.error()은 오류 로그를 기록합니다. 이러한 로그는 Azure Functions의 로그 출력에 기록되어 확인할 수 있습니다.

Monitoring

Azure Functions를 모니터링하면 앱의 상태를 지속적으로 감시하고 성능 이슈를 해결할 수 있습니다. Azure Portal의 모니터링 기능을 사용하면 Azure Functions에서 발생하는 로그와 메트릭 데이터를 쉽게 확인할 수 있습니다.

또한, Azure Application Insights와 같은 외부 도구를 사용하여 더 고급화된 모니터링을 수행할 수도 있습니다. Application Insights는 사용자 지정된 로그 및 지표 데이터를 수집하고 분석하는 강력한 애플리케이션 모니터링 솔루션입니다. 다음은 Azure Functions에서 Application Insights와 함께 사용하는 예시 코드입니다.

import logging
import os
import azure.functions as func
import opencensus.ext.azure as azext
from opencensus.ext.azure.log_exporter import AzureLogHandler

# 로깅을 위한 Azure Application Insights 연결 설정
connection_string = os.environ.get('APPLICATION_INSIGHTS_CONNECTION_STRING')
logger = logging.getLogger(__name__)
logger.addHandler(AzureLogHandler(connection_string=connection_string))

def main(req: func.HttpRequest) -> func.HttpResponse:
    # 로그를 Application Insights에 기록
    logger.info("This is an informational log")
    logger.warning("This is a warning log")
    logger.error("This is an error log")

    return func.HttpResponse("Logging and monitoring example")

위 코드에서는 APPLICATION_INSIGHTS_CONNECTION_STRING 환경 변수를 사용하여 Azure Application Insights와 연결합니다. logger.info(), logger.warning(), logger.error()를 사용하여 로그를 Application Insights에 기록합니다. 이를 통해 더 상세한 로그 및 지표 데이터를 수집하고 분석할 수 있습니다.

결론

Azure Functions를 사용하여 파이썬 애플리케이션을 개발하고 실행할 때, 로깅과 모니터링은 중요한 요소입니다. Azure Functions의 내장 로그 기능과 외부 도구를 통해 로그와 메트릭 데이터를 기록하고 모니터링할 수 있습니다. 이를 통해 애플리케이션의 상태를 파악하고 성능 이슈를 식별하여 좀 더 안정적이고 효율적인 애플리케이션을 개발할 수 있습니다.

참고 자료