Edit

Share via


Configure logging in Azure SDK client libraries for JavaScript

This article explains how to configure logging in Azure SDK libraries for JavaScript. Enabling logging helps you diagnose authentication issues, troubleshoot credential chains, and gain visibility into SDK operations.

To enable logging you can use either of the options below:

  • Set the AZURE_LOG_LEVEL=verbose environment variable to turn on logging.
  • Use the @azure/logger package in your source code.

Valid log levels include verbose, info, warning, and error.

Note

The Azure Storage code shown in this article assumes the storage resource has been configured with the appropriate Microsoft Entra roles. Learn more: Authorize access to blobs using Microsoft Entra ID.

Prerequisites

  • An Azure subscription: Create one for free
  • Node.js LTS
  • Optional, a developer tool such as Azure CLI used for authentication in a local development environment. To create the necessary context, sign in with the Azure CLI.

Enable logging with environment variable

Start the application with the environment variable for a simple way to enable logging.

AZURE_LOG_LEVEL=verbose node index.js

Set environment variables

You can also add environment variables to a .env file in your project root. Create a file named .env and add the following content.

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>

Enable logging with logger package in source code

The following code sample uses the @azure/logger package to debug the Azure SDK client libraries.

Configure logging for specific services

In addition to setting a global log level, you can configure different log levels for specific Azure services directly in your code:

// 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

This approach gives you fine-grained control over logging verbosity when working with multiple Azure services in the same application.

  1. Create index.js with the following code.

    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. Create the project and install the npm dependencies.

    npm init -y
    npm pkg set type=module
    npm install @azure/identity @azure/storage-blob @azure/logger
    
  3. Sign in to your Azure subscription in your local environment with Azure CLI.

    az login
    
  4. Run the app with an environment variable file. The --env-file option was introduced in Node.js 20.6.0.

    node --env-file .env index.js
    
  5. Find the successful credential in the output. ChainedTokenCredential allows your code to seamlessly switch between authentication methods, first trying ManagedIdentityCredential (for production environments like Azure App Service) and then falling back to AzureCliCredential (for local development), with logs showing which credential succeeded.

Prerequisites

Enable logging with environment variable

Start the application with the environment variable for a simple way to enable logging.

AZURE_LOG_LEVEL=verbose node index.js

Set environment variables

You can also add environment variables to a .env file in your project root. Create a file named .env and add the following content.

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>

Enable logging with logger package in source code

The following code sample uses the @azure/logger package to debug the Azure SDK client libraries.

Configure logging for specific services

In addition to setting a global log level, you can configure different log levels for specific Azure services directly in your code:

// 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

This approach gives you fine-grained control over logging verbosity when working with multiple Azure services in the same application.

  1. Create index.ts with the following code.

    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. Create the project and install the npm dependencies.

    npm init -y
    npm pkg set type=module
    npm install @azure/identity @azure/storage-blob @types/node @azure/logger
    
  3. Sign in to your Azure subscription in your local environment with Azure CLI.

    az login
    
  4. Build the application.

    tsc
    
  5. Run the app with an environment variable file. The --env-file option was introduced in Node.js 20.6.0.

    node --env-file .env index.js
    
  6. Find the successful credential in the output - the ChainedTokenCredential allows your code to seamlessly switch between authentication methods, first trying ManagedIdentityCredential (for production environments like Azure App Service) and then falling back to AzureCliCredential (for local development), with logs showing which credential succeeded.

Additional resources