Skip to content

Commit

Permalink
Added Monitor Diagnostic Settings. (#221)
Browse files Browse the repository at this point in the history
  • Loading branch information
Hovsep authored Mar 20, 2018
1 parent cadf414 commit 50bfca3
Show file tree
Hide file tree
Showing 42 changed files with 12,689 additions and 747 deletions.
151 changes: 151 additions & 0 deletions Samples/EventHub/ManageEventHubEvents.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using Microsoft.Azure.Management.CosmosDB.Fluent.Models;
using Microsoft.Azure.Management.Eventhub.Fluent;
using Microsoft.Azure.Management.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions;
using Microsoft.Azure.Management.Samples.Common;
using Microsoft.Azure.Management.Storage.Fluent;
using System;

/**
* Azure Event Hub sample for managing event hub models.
* - Create a DocumentDB instance
* - Creates a Event Hub namespace and an Event Hub in it
* - Retrieve the root namespace authorization rule
* - Enable diagnostics on a existing cosmosDB to stream events to event hub
*/
namespace ManageEventHubEvents
{
public class Program
{
public static void RunSample(IAzure azure)
{
string storageAccountConnectionStringFormat = "DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1};EndpointSuffix=core.windows.net";
Region region = Region.USEast;
string rgName = SdkContext.RandomResourceName("rgEvHb", 15);
string namespaceName = SdkContext.RandomResourceName("ns", 15);
string storageAccountName = SdkContext.RandomResourceName("stg", 15);
string eventHubName = "FirstEventHub";
string diagnosticSettingId = null;

try
{
//=============================================================
// Creates a Cosmos DB.
//
var docDb = azure.CosmosDBAccounts
.Define(namespaceName)
.WithRegion(region)
.WithNewResourceGroup(rgName)
.WithKind(DatabaseAccountKind.MongoDB)
.WithEventualConsistency()
.WithWriteReplication(Region.USWest)
.WithReadReplication(Region.USCentral)
.Create();

Utilities.Log("Created a DocumentDb instance.");
Utilities.Print(docDb);
//=============================================================
// Creates a Event Hub namespace and an Event Hub in it.
//

Utilities.Log("Creating event hub namespace and event hub");

var ehNamespace = azure.EventHubNamespaces
.Define(namespaceName)
.WithRegion(region)
.WithExistingResourceGroup(rgName)
.WithNewEventHub(eventHubName)
.Create();

Utilities.Log($"Created event hub namespace {ehNamespace.Name} and event hub {eventHubName}");
Utilities.Print(ehNamespace);

//=============================================================
// Retrieve the root namespace authorization rule.
//

Utilities.Log("Retrieving the namespace authorization rule");

var eventHubAuthRule = azure.EventHubNamespaces
.AuthorizationRules
.GetByName(ehNamespace.ResourceGroupName, ehNamespace.Name, "RootManageSharedAccessKey");

Utilities.Log("Namespace authorization rule Retrieved");

//=============================================================
// Enable diagnostics on a cosmosDB to stream events to event hub
//

Utilities.Log("Enabling diagnostics events of a cosmosdb to stream to event hub");

// Store Id of created Diagnostic settings only for clean-up
var ds = azure.DiagnosticSettings
.Define("DiaEventHub")
.WithResource(docDb.Id)
.WithEventHub(eventHubAuthRule.Id, eventHubName)
.WithLog("DataPlaneRequests", 0)
.WithLog("MongoRequests", 0)
.WithMetric("AllMetrics", TimeSpan.FromMinutes(5), 0)
.Create();

Utilities.Print(ds);
diagnosticSettingId = ds.Id;

Utilities.Log("Streaming of diagnostics events to event hub is enabled");

//=============================================================
// Listen for events from event hub using Event Hub dataplane APIs.
}
finally
{
try
{
if (diagnosticSettingId != null)
{
Utilities.Log("Deleting Diagnostic Setting: " + diagnosticSettingId);
azure.DiagnosticSettings.DeleteById(diagnosticSettingId);
}
azure.ResourceGroups.DeleteByName(rgName);
}
catch (NullReferenceException)
{
Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
}
catch (Exception ex)
{
Utilities.Log(ex);
}
}
}

public static void Main(string[] args)
{
try
{
//=================================================================
// Authenticate
var credentials = SdkContext.AzureCredentialsFactory.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));

var azure = Azure
.Configure()
.WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
.Authenticate(credentials)
.WithDefaultSubscription();

// Print selected subscription
Utilities.Log("Selected subscription: " + azure.SubscriptionId);

RunSample(azure);
}
catch (Exception ex)
{
Utilities.Log(ex);
}
}
}
}
1 change: 1 addition & 0 deletions Samples/Monitor/QueryMetricsAndActivityLogs.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ public static void RunSample(IAzure azure)
.Execute();

Utilities.Log("Metrics for '" + storageAccount.Id + "':");
Utilities.Log("Namespacse: " + metricCollection.Namespace);
Utilities.Log("Query time: " + metricCollection.Timespan);
Utilities.Log("Time Grain: " + metricCollection.Interval);
Utilities.Log("Cost: " + metricCollection.Cost);
Expand Down
50 changes: 50 additions & 0 deletions Samples/Utilities.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
using Microsoft.Azure.Management.Locks.Fluent;
using Microsoft.Azure.Management.Msi.Fluent;
using Microsoft.Azure.Management.Eventhub.Fluent;
using Microsoft.Azure.Management.Monitor.Fluent;

namespace Microsoft.Azure.Management.Samples.Common
{
Expand Down Expand Up @@ -330,6 +331,55 @@ public static void Print(ITopicAuthorizationRule topicAuthorizationRule)
Log(builder.ToString());
}

public static void Print(IDiagnosticSetting resource)
{
StringBuilder info = new StringBuilder("Diagnostic Setting: ")
.Append("\n\tId: ").Append(resource.Id)
.Append("\n\tAssociated resource Id: ").Append(resource.ResourceId)
.Append("\n\tName: ").Append(resource.Name)
.Append("\n\tStorage Account Id: ").Append(resource.StorageAccountId)
.Append("\n\tEventHub Namespace Autorization Rule Id: ").Append(resource.EventHubAuthorizationRuleId)
.Append("\n\tEventHub name: ").Append(resource.EventHubName)
.Append("\n\tLog Analytics workspace Id: ").Append(resource.WorkspaceId);

if (resource.Logs != null && resource.Logs.Any())
{
info.Append("\n\tLog Settings: ");
foreach (var ls in resource.Logs)
{
info.Append("\n\t\tCategory: ").Append(ls.Category);
info.Append("\n\t\tRetention policy: ");
if (ls.RetentionPolicy != null)
{
info.Append(ls.RetentionPolicy.Days + " days");
}
else
{
info.Append("NONE");
}
}
}
if (resource.Metrics != null && resource.Metrics.Any())
{
info.Append("\n\tMetric Settings: ");
foreach (var ls in resource.Metrics)
{
info.Append("\n\t\tCategory: ").Append(ls.Category);
info.Append("\n\t\tTimegrain: ").Append(ls.TimeGrain);
info.Append("\n\t\tRetention policy: ");
if (ls.RetentionPolicy != null)
{
info.Append(ls.RetentionPolicy.Days + " days");
}
else
{
info.Append("NONE");
}
}
}
Log(info.ToString());
}

public static void Print(ISearchService searchService)
{
var adminKeys = searchService.GetAdminKeys();
Expand Down
7 changes: 6 additions & 1 deletion Samples/samples.json
Original file line number Diff line number Diff line change
Expand Up @@ -330,7 +330,12 @@
"githubPath": "Azure-Samples/monitor-dotnet-query-metrics-activitylogs",
"description": "Getting metrics and activity logs for a resource."
},

{
"owner": "hovsepm",
"filePath": "Samples/EventHub/ManageEventHubEvents.cs",
"githubPath": "Azure-Samples/eventhub-dotnet-manage-event-hub-events",
"description": "Getting started on managing event hub, diagnostic settings and associated resources using C#"
},

{
"owner": "jianghaolu",
Expand Down
Loading

0 comments on commit 50bfca3

Please sign in to comment.