Use Azure Monitor SDK to list recent resource operations

Use the Azure Monitor SDK to list the most recent resource operations in your subscription. Operations can be filtered by a date range (within the last 10 days), and a resource group. Examples of operations can include resource creation, stopping or starting a resource such as web app or virtual machine, and retrieving a connection string.

Set up your development environment

Create Azure operations

In order for the Azure Monitor to return results with this sample code, your subscription has to have resources with operations. An operation can be as simple as starting a web app, or getting a connection string. These operations can happen from any source that uses Azure including the Azure portal, your local installation of the Azure CLI, or any programmatic access to your resources through REST APIs or the Azure SDK.

If you are new to Azure, the Azure portal is the quickest way to create monitor entries to use this sample code.

Find a free resource then create it in the Azure portal.

Use Azure Monitor SDK with JavaScript

  1. Create a file or copy the file from GitHub.

    const {
      ClientSecretCredential,
      DefaultAzureCredential,
    } = require("@azure/identity");
    const { MonitorManagementClient } = require("@azure/arm-monitor");
    const dayjs = require("dayjs");
    const { prettyPrint } = require("@base2/pretty-print-object");
    
    // resource group - returns all resource groups if not specified
    const resourceGroupName = "";
    
    // days needs to be less than or equal to 90
    const daysAgo = 10;
    
    // filter
    // https://docs.microsoft.com/en-us/javascript/api/@azure/arm-monitor/activitylogs?view=azure-node-latest#list_string__ActivityLogsListOptionalParams__ServiceCallback_EventDataCollection__
    const greaterThanIsoTime = dayjs().subtract(daysAgo, "day").toISOString();
    const lessThanIsoTime = new Date().toISOString();
    let filter = `eventTimestamp ge '${greaterThanIsoTime}' and eventTimestamp le '${lessThanIsoTime}'`;
    filter += resourceGroupName
      ? ` and resourceGroupName eq '${resourceGroupName}'`
      : null;
    
    // Azure authentication in environment variables for DefaultAzureCredential
    let credentials = null;
    const tenantId =
      process.env["AZURE_TENANT_ID"] || "REPLACE-WITH-YOUR-TENANT-ID";
    const clientId =
      process.env["AZURE_CLIENT_ID"] || "REPLACE-WITH-YOUR-CLIENT-ID";
    const secret =
      process.env["AZURE_CLIENT_SECRET"] || "REPLACE-WITH-YOUR-CLIENT-SECRET";
    const subscriptionId =
      process.env["AZURE_SUBSCRIPTION_ID"] || "REPLACE-WITH-YOUR-SUBSCRIPTION_ID";
    
    if (process.env.production) {
      // production
      credentials = new DefaultAzureCredential();
    } else {
      // development
      credentials = new ClientSecretCredential(tenantId, clientId, secret);
      console.log("development");
    }
    
    try {
      // use credential to authenticate with Azure SDKs
      const client = new MonitorManagementClient(credentials, subscriptionId);
    
      const arrObjects = new Array();
      for await (const element of client.activityLogs.list(filter)) {
        arrObjects.push({
          resourceGroupName: element?.resourceGroupName,
          action: element?.authorization?.action,
          user:
            element?.claims?.[
              "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"
            ],
          resourceProviderName: element?.resourceProviderName,
          resourceType: element?.resourceType,
          operationName: element.operationName,
          status: element.status,
          eventTimestamp: element.eventTimestamp,
        });
      }
      console.log(prettyPrint(arrObjects));
    } catch (err) {
      console.log("An error occurred:");
      console.log(err);
    }
    
    /*
    
    Example element:
    
      {
        resourceGroupName: 'johnsmith-temp',
        action: 'Microsoft.DocumentDB/databaseAccounts/listConnectionStrings/action',
        user: 'johnsmith@contoso.com',
        resourceProviderName: {
          value: 'Microsoft.DocumentDB',
          localizedValue: 'Microsoft.DocumentDB'
        },
        resourceType: {
          value: 'Microsoft.DocumentDB/databaseAccounts',
          localizedValue: 'Microsoft.DocumentDB/databaseAccounts'
        },
        operationName: {
          value: 'Microsoft.DocumentDB/databaseAccounts/listConnectionStrings/action',
          localizedValue: 'Get Connection Strings'
        },
        status: { value: 'Succeeded', localizedValue: 'Succeeded' },
        eventTimestamp: 2021-09-21T17:27:22.727Z
      },
    
    */
    
  2. Install the npm packages used in the Azure work:

    npm init -y && install @azure/identity @azure/arm-monitor
    
  3. Install the npm packages used to support the day filtering and pretty JSON printing:

    npm install dayjs @base2/pretty-print-object
    
  4. Run the code to see your subscription operation history:

    node resource-creation-history.js
    

Next steps