Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Monitoring Queue Length with AzureFunctions w/MSI Auth to Storage Queue
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.Azure.Services.AppAuthentication;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Queue;
using MyFunction.Extensions;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace StorageFunctions
public class MonitorMetrics
private static readonly string key = TelemetryConfiguration.Active.InstrumentationKey = Environment.GetEnvironmentVariable("APPINSIGHTS_INSTRUMENTATIONKEY", EnvironmentVariableTarget.Process);
private static readonly TelemetryClient telemetry = new TelemetryClient() { InstrumentationKey = key };
public static async Task MonitorQueueLength(
[TimerTrigger("*/30 * * * * *")]TimerInfo myTimer,
ExecutionContext context,
ILogger log)
log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
// connect to Azure Storage
var queueClient = context.IsAzureEnvironment()
? await CreateQueueClientAsync("your_storage_account_name")
: CreateQueueClient(Environment.GetEnvironmentVariable("queue_storage_connection_string"));
var queueNames = new [] {"queuename" };
var tasks = queueNames.Select(async x =>
// get a reference to the queue and retrieve the queue length
var queue = queueClient.GetQueueReference(x);
await queue.FetchAttributesAsync();
var length = queue.ApproximateMessageCount;
// log the length
log.LogInformation($"{x}: {length}");
await Task.WhenAll(tasks);
catch (Exception ex)
log.LogError($"{ex.Message}, {ex.GetType()}, {ex.StackTrace}");
private static CloudQueueClient CreateQueueClient(string connectionString)
var account = CloudStorageAccount.Parse(connectionString);
var queueClient = account.CreateCloudQueueClient();
return queueClient;
private static async Task<CloudQueueClient> CreateQueueClientAsync(string storageAccountName)
var azureServiceTokenProvider = new AzureServiceTokenProvider();
var accessToken = await azureServiceTokenProvider.GetAccessTokenAsync("");
var tokenCredential = new TokenCredential(accessToken);
var storageCredentials = new StorageCredentials(tokenCredential);
var queueClient = new CloudQueueClient(new StorageUri(new Uri($"https://{storageAccountName}")), storageCredentials);
return queueClient;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment