JavaScript용 Azure SDK 클라이언트 라이브러리에서 로깅 구성

이 문서에서는 JavaScript용 Azure SDK 라이브러리에서 로깅을 구성하는 방법을 설명합니다. 로깅을 사용하도록 설정하면 인증 문제를 진단하고 자격 증명 체인 문제를 해결하며 SDK 작업에 대한 가시성을 얻을 수 있습니다.

로깅을 사용하도록 설정하려면 아래 옵션 중 하나를 사용할 수 있습니다.

  • 로깅을 AZURE_LOG_LEVEL=verbose 켜도록 환경 변수를 설정합니다.
  • 소스 코드에서 @azure/logger 패키지를 사용합니다.

유효한 로그 수준에는 verbose, info, warningerror가 포함됩니다.

비고

이 문서에 표시된 Azure Storage 코드는 스토리지 리소스가 적절한 Microsoft Entra 역할로 구성되었다고 가정합니다. 자세한 정보: Microsoft Entra ID를 사용하여 Blob에 대한 액세스 권한을 부여합니다.

필수 조건

  • Azure 구독: 무료로 구독 만들기
  • Node.js LTS
  • 선택 사항으로, 로컬 개발 환경에서 인증에 사용되는 Azure CLI 와 같은 개발자 도구입니다. 필요한 컨텍스트를 만들려면 Azure CLI로 로그인합니다.

환경 변수로 로깅 활성화

로깅을 사용하도록 설정하는 간단한 방법을 위해 환경 변수를 사용하여 애플리케이션을 시작합니다.

AZURE_LOG_LEVEL=verbose node index.js

환경 변수 설정

프로젝트 루트의 파일에 환경 변수를 .env 추가할 수도 있습니다. 명명 .env 된 파일을 만들고 다음 콘텐츠를 추가합니다.

AZURE_LOG_LEVEL=verbose
AZURE_CLIENT_ID=<YOUR_CLIENT_ID>
AZURE_STORAGE_ACCOUNT_NAME=<YOUR_STORAGE_ACCOUNT_NAME>
AZURE_STORAGE_CONTAINER_NAME=<YOUR_STORAGE_CONTAINER_NAME>

소스 코드에서 logger 패키지를 사용하여 로깅 활성화

다음 코드 샘플에서는 @azure/로거 패키지를 사용하여 Azure SDK 클라이언트 라이브러리를 디버그합니다.

특정 서비스에 대한 로깅 구성

전역 로그 수준을 설정하는 것 외에도 코드에서 직접 특정 Azure 서비스에 대해 다른 로그 수준을 구성할 수 있습니다.

// Import service-specific setLogLevel functions
import { setLogLevel as setIdentityLogLevel } from "@azure/identity";
import { setLogLevel as setStorageLogLevel } from "@azure/storage-blob";

// Set different log levels for different services
setIdentityLogLevel("verbose");  // Detailed logs for identity operations
setStorageLogLevel("warning");   // Only warnings and errors for storage operations

이 방법을 사용하면 동일한 애플리케이션에서 여러 Azure 서비스를 사용할 때 자세한 정보 로깅을 세밀하게 제어할 수 있습니다.

  1. 다음 코드로 index.js를 생성합니다.

    import {
        ChainedTokenCredential,
        ManagedIdentityCredential,
        AzureCliCredential
    } from "@azure/identity";
    import { BlobServiceClient } from "@azure/storage-blob";
    import { AzureLogger, setLogLevel } from "@azure/logger";
    
    // Check required environment variables
    if (!process.env.AZURE_STORAGE_ACCOUNT_NAME) {
        throw new Error("AZURE_STORAGE_ACCOUNT_NAME environment variable is required");
    }
    
    if (!process.env.AZURE_STORAGE_CONTAINER_NAME) {
        throw new Error("AZURE_STORAGE_CONTAINER_NAME environment variable is required");
    }
    
    // Client ID is optional and only used in production environments
    // No need to check for its existence
    
    // Turn on debugging for all Azure SDKs
    setLogLevel("verbose");
    
    // Configure the logger to use console.
    AzureLogger.log = (...args)=> {
        console.log(...args);
    };
    
    const credential = new ChainedTokenCredential(
        new ManagedIdentityCredential({ clientId: process.env.AZURE_CLIENT_ID }),
        new AzureCliCredential()
    );
    
    const blobServiceClient = new BlobServiceClient(
        `https://${process.env.AZURE_STORAGE_ACCOUNT_NAME}.blob.core.windows.net`,
        credential
    );
    // get container properties
    const containerClient = blobServiceClient.getContainerClient(process.env.AZURE_STORAGE_CONTAINER_NAME);
    
    async function main() {
        try {
            const properties = await containerClient.getProperties();
    
            console.log(properties);
        } catch (err) {
            const error = err;
            console.error("Error retrieving container properties:", error.message);
            throw error;
        }
    }
    
    main().catch((err) => {
        console.error("Error running sample:", err.message);
        process.exit(1);
    });
    
  2. 프로젝트를 만들고 npm 종속성을 설치합니다.

    npm init -y
    npm pkg set type=module
    npm install @azure/identity @azure/storage-blob @azure/logger
    
  3. Azure CLI를 사용하여 로컬 환경에서 Azure 구독에 로그인합니다.

    az login
    
  4. 환경 변수 파일을 사용하여 앱을 실행합니다. 이 --env-file 옵션은 Node.js 20.6.0에서 도입되었습니다.

    node --env-file .env index.js
    
  5. 출력에서 성공적인 자격 증명을 찾습니다. ChainedTokenCredential을 사용하면 코드에서 인증 방법 간에 원활하게 전환할 수 있습니다. 먼저 ManagedIdentityCredential을 시도하고(Azure App Service와 같은 프로덕션 환경용), 그런 다음 AzureCliCredential로 대체됩니다(로컬 개발용). 또한 어떤 자격 증명이 성공했는지 로그에 표시됩니다.

필수 조건

환경 변수로 로깅 활성화

로깅을 사용하도록 설정하는 간단한 방법을 위해 환경 변수를 사용하여 애플리케이션을 시작합니다.

AZURE_LOG_LEVEL=verbose node index.js

환경 변수 설정

프로젝트 루트의 파일에 환경 변수를 .env 추가할 수도 있습니다. 명명 .env 된 파일을 만들고 다음 콘텐츠를 추가합니다.

AZURE_LOG_LEVEL=verbose
AZURE_CLIENT_ID=<YOUR_CLIENT_ID>
AZURE_STORAGE_ACCOUNT_NAME=<YOUR_STORAGE_ACCOUNT_NAME>
AZURE_STORAGE_CONTAINER_NAME=<YOUR_STORAGE_CONTAINER_NAME>

소스 코드에서 logger 패키지를 사용하여 로깅 활성화

다음 코드 샘플에서는 @azure/로거 패키지를 사용하여 Azure SDK 클라이언트 라이브러리를 디버그합니다.

특정 서비스에 대한 로깅 구성

전역 로그 수준을 설정하는 것 외에도 코드에서 직접 특정 Azure 서비스에 대해 다른 로그 수준을 구성할 수 있습니다.

// Import service-specific setLogLevel functions
import { setLogLevel as setIdentityLogLevel } from "@azure/identity";
import { setLogLevel as setStorageLogLevel } from "@azure/storage-blob";

// Set different log levels for different services
setIdentityLogLevel("verbose");  // Detailed logs for identity operations
setStorageLogLevel("warning");   // Only warnings and errors for storage operations

이 방법을 사용하면 동일한 애플리케이션에서 여러 Azure 서비스를 사용할 때 자세한 정보 로깅을 세밀하게 제어할 수 있습니다.

  1. 다음 코드를 사용하여 index.ts를 생성합니다.

    import {
        ChainedTokenCredential,
        ManagedIdentityCredential,
        AzureCliCredential
    } from "@azure/identity";
    import { BlobServiceClient, ContainerGetPropertiesResponse } from "@azure/storage-blob";
    import { AzureLogger, setLogLevel } from "@azure/logger";
    
    // Check required environment variables
    if (!process.env.AZURE_STORAGE_ACCOUNT_NAME) {
        throw new Error("AZURE_STORAGE_ACCOUNT_NAME environment variable is required");
    }
    
    if (!process.env.AZURE_STORAGE_CONTAINER_NAME) {
        throw new Error("AZURE_STORAGE_CONTAINER_NAME environment variable is required");
    }
    
    // Client ID is optional and only used in production environments
    // No need to check for its existence
    
    // Turn on debugging for all Azure SDKs
    setLogLevel("verbose");
    
    // Configure the logger to use console.log with TypeScript type safety
    AzureLogger.log = (...args: unknown[]): void => {
        console.log(...args);
    };
    
    const credential = new ChainedTokenCredential(
        new ManagedIdentityCredential({ clientId: process.env.AZURE_CLIENT_ID }),
        new AzureCliCredential()
    );
    
    const blobServiceClient = new BlobServiceClient(
        `https://${process.env.AZURE_STORAGE_ACCOUNT_NAME}.blob.core.windows.net`,
        credential
    );
    // get container properties
    const containerClient = blobServiceClient.getContainerClient(process.env.AZURE_STORAGE_CONTAINER_NAME);
    
    async function main(): Promise<void> {
        try {
            const properties: ContainerGetPropertiesResponse = await containerClient.getProperties();
    
            console.log(properties);
        } catch (err) {
            const error = err as Error;
            console.error("Error retrieving container properties:", error.message);
            throw error;
        }
    }
    
    main().catch((err: Error) => {
        console.error("Error running sample:", err.message);
        process.exit(1);
    });
    
  2. 프로젝트를 만들고 npm 종속성을 설치합니다.

    npm init -y
    npm pkg set type=module
    npm install @azure/identity @azure/storage-blob @types/node @azure/logger
    
  3. Azure CLI를 사용하여 로컬 환경에서 Azure 구독에 로그인합니다.

    az login
    
  4. 애플리케이션을 빌드합니다.

    tsc
    
  5. 환경 변수 파일을 사용하여 앱을 실행합니다. 이 --env-file 옵션은 Node.js 20.6.0에서 도입되었습니다.

    node --env-file .env index.js
    
  6. 출력에서 성공한 자격 증명을 확인합니다. ChainedTokenCredential을 사용하면 코드가 인증 방법 간에 원활하게 전환할 수 있으며, 먼저 ManagedIdentityCredential(Azure App Service와 같은 프로덕션 환경용)을 시도한 다음 AzureCliCredential(로컬 개발용)로 대체하고, 어떤 자격 증명이 성공했는지는 로그에 표시됩니다.

추가 리소스