-
Notifications
You must be signed in to change notification settings - Fork 355
/
DictionaryLoggerScope.cs
93 lines (79 loc) · 2.85 KB
/
DictionaryLoggerScope.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;
namespace Microsoft.Azure.WebJobs.Logging
{
internal class DictionaryLoggerScope
{
private static AsyncLocal<DictionaryLoggerScope> _value = new AsyncLocal<DictionaryLoggerScope>();
private DictionaryLoggerScope(IReadOnlyDictionary<string, object> state, DictionaryLoggerScope parent)
{
State = state;
Parent = parent;
}
internal IReadOnlyDictionary<string, object> State { get; private set; }
internal DictionaryLoggerScope Parent { get; private set; }
public static DictionaryLoggerScope Current
{
get
{
return _value.Value;
}
set
{
_value.Value = value;
}
}
public static IDisposable Push(object state)
{
IDictionary<string, object> stateValues;
if (state is IEnumerable<KeyValuePair<string, object>> stateEnum)
{
// Convert this to a dictionary as we have scenarios where we cannot have duplicates. In this
// case, if there are dupes, the later entry wins.
stateValues = new Dictionary<string, object>();
foreach (var entry in stateEnum)
{
stateValues[entry.Key] = entry.Value;
}
}
else
{
// There's nothing we can do with other states.
return null;
}
Current = new DictionaryLoggerScope(new ReadOnlyDictionary<string, object>(stateValues), Current);
return new DisposableScope();
}
// Builds a state dictionary of all scopes. If an inner scope
// contains the same key as an outer scope, it overwrites the value.
public static IDictionary<string, object> GetMergedStateDictionary()
{
IDictionary<string, object> scopeInfo = new Dictionary<string, object>();
var current = Current;
while (current != null)
{
foreach (var entry in current.State)
{
// inner scopes win
if (!scopeInfo.Keys.Contains(entry.Key))
{
scopeInfo.Add(entry);
}
}
current = current.Parent;
}
return scopeInfo;
}
private class DisposableScope : IDisposable
{
public void Dispose()
{
Current = Current.Parent;
}
}
}
}