Created
March 27, 2019 14:30
-
-
Save guitarrapc/c39eeed2933ab8c8147e4243b1fd0aaa to your computer and use it in GitHub Desktop.
Azure resource monitoring with Azure Functions v2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.ApplicationInsights; | |
using Microsoft.ApplicationInsights.Extensibility; | |
using Microsoft.Azure.WebJobs; | |
using Microsoft.Extensions.Logging; | |
using Microsoft.WindowsAzure.Storage; | |
using System; | |
using System.Linq; | |
using System.Threading; | |
using System.Threading.Tasks; | |
namespace AzureMonitoring | |
{ | |
public class MonitorMetrics | |
{ | |
private static string key = TelemetryConfiguration.Active.InstrumentationKey = Environment.GetEnvironmentVariable("APPINSIGHTS_INSTRUMENTATIONKEY", EnvironmentVariableTarget.Process); | |
private static TelemetryClient telemetry = new TelemetryClient() { InstrumentationKey = key }; | |
[FunctionName("MonitorQueueLength")] | |
public static async Task MonitorQueueLength([TimerTrigger("*/10 * * * * *")]TimerInfo myTimer,ILogger log) | |
{ | |
log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}"); | |
// connect to Azure Storage | |
var connectionString = Environment.GetEnvironmentVariable("queue_storage_connection_string"); | |
var account = CloudStorageAccount.Parse(connectionString); | |
var queueClient = account.CreateCloudQueueClient(); | |
var queueNames = new [] {"myqueue", "myqueue-poison"}; | |
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}"); | |
telemetry.GetMetric($"QueueLength.{x}").TrackValue(length); | |
}); | |
await Task.WhenAll(tasks); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment