forked from Azure/azure-sdk-for-net
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Sample4_Logging.cs
75 lines (65 loc) · 2.55 KB
/
Sample4_Logging.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
using NUnit.Framework;
using System;
using System.Diagnostics;
using System.Diagnostics.Tracing;
namespace Azure.ApplicationModel.Configuration.Samples
{
[Category("Live")]
public partial class ConfigurationSamples
{
// ConfigurationClient logs lots of useful information automatically to .NET's EventSource.
// This sample illustrate how to control and access the log information.
[Test]
public void Logging()
{
// Retrieve the connection string from the configuration store.
// You can get the string from your Azure portal.
var connectionString = Environment.GetEnvironmentVariable("APP_CONFIG_CONNECTION");
var client = new ConfigurationClient(connectionString);
// Setup a listener to monitor logged events.
var listener = new ConsoleEventListener();
listener.EnableEvents(EventLevel.LogAlways);
Response<ConfigurationSetting> setResponse = client.Set(new ConfigurationSetting("some_key", "some_value"));
if (setResponse.GetRawResponse().Status != 200)
{
throw new Exception("could not set configuration setting");
}
// Delete the setting when you don't need it anymore.
client.Delete("some_key");
}
}
public class ConsoleEventListener : EventListener
{
const string SOURCE_NAME = "AzureSDK";
EventLevel _enabled;
EventSource _source;
protected override void OnEventSourceCreated(EventSource eventSource)
{
base.OnEventSourceCreated(eventSource);
if (eventSource.Name == SOURCE_NAME) {
_source = eventSource;
if (_enabled != default) {
EnableEvents(_source, _enabled);
}
}
}
public void EnableEvents(EventLevel level)
{
_enabled = level;
if (_source != null) {
EnableEvents(_source, _enabled);
}
}
protected override void OnEventWritten(EventWrittenEventArgs eventData)
{
if (eventData.EventSource.Name == SOURCE_NAME) {
var formatted = eventData.EventName + " : " + eventData.Payload[0].ToString();
Console.WriteLine(formatted);
Debug.WriteLine(formatted);
}
}
}
}