次の方法で共有


JavaScript 用の Azure SDK クライアント ライブラリでログ記録を構成する

この記事では、JavaScript 用の Azure SDK ライブラリでログ記録を構成する方法について説明します。 ログ記録を有効にすると、認証の問題の診断、資格情報チェーンのトラブルシューティング、SDK 操作の可視性の向上に役立ちます。

ログ記録を有効にするには、次のいずれかのオプションを使用できます。

  • ログ記録を有効にするには、 AZURE_LOG_LEVEL=verbose 環境変数を設定します。
  • ソース コードで @azure/logger パッケージを使用します。

有効なログ レベルには、 verboseinfowarning、および errorが含まれます。

この記事に示す 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>

ソース コードでロガー パッケージを使用してログ記録を有効にする

次のコード サンプルでは、 @azure/logger パッケージを使用して 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 サブスクリプション: 無料で作成する
  • Node.js LTS
  • TypeScript
  • オプション。ローカル開発環境での認証に使用される 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>

ソース コードでロガー パッケージを使用してログ記録を有効にする

次のコード サンプルでは、 @azure/logger パッケージを使用して 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 (ローカル開発の場合) にフォールバックし、成功した資格情報を示すログを表示できます。

その他のリソース