forked from serilog/serilog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PropertyValueConverter-net40.cs
204 lines (179 loc) · 8.7 KB
/
PropertyValueConverter-net40.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
// Copyright 2014 Serilog Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Serilog.Core;
using Serilog.Debugging;
using Serilog.Events;
using Serilog.Parsing;
using Serilog.Policies;
namespace Serilog.Parameters
{
// Values in Serilog are simplified down into a lowest-common-denominator internal
// type system so that there is a better chance of code written with one sink in
// mind working correctly with any other. This technique also makes the programmer
// writing a log event (roughly) in control of the cost of recording that event.
partial class PropertyValueConverter : ILogEventPropertyFactory, ILogEventPropertyValueFactory
{
static readonly HashSet<Type> BuiltInScalarTypes = new HashSet<Type>
{
typeof(bool),
typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint),
typeof(long), typeof(ulong), typeof(float), typeof(double), typeof(decimal),
typeof(string),
typeof(DateTime), typeof(DateTimeOffset), typeof(TimeSpan),
typeof(Guid), typeof(Uri)
};
readonly IDestructuringPolicy[] _destructuringPolicies;
readonly IScalarConversionPolicy[] _scalarConversionPolicies;
readonly int _maximumDestructuringDepth;
public PropertyValueConverter(int maximumDestructuringDepth, IEnumerable<Type> additionalScalarTypes, IEnumerable<IDestructuringPolicy> additionalDestructuringPolicies)
{
if (additionalScalarTypes == null) throw new ArgumentNullException("additionalScalarTypes");
if (additionalDestructuringPolicies == null) throw new ArgumentNullException("additionalDestructuringPolicies");
if (maximumDestructuringDepth < 0) throw new ArgumentOutOfRangeException("maximumDestructuringDepth");
_maximumDestructuringDepth = maximumDestructuringDepth;
_scalarConversionPolicies = new IScalarConversionPolicy[]
{
new SimpleScalarConversionPolicy(BuiltInScalarTypes.Concat(additionalScalarTypes)),
new NullableScalarConversionPolicy(),
new EnumScalarConversionPolicy(),
new ByteArrayScalarConversionPolicy(),
new ReflectionTypesScalarConversionPolicy()
};
_destructuringPolicies = additionalDestructuringPolicies
.Concat(new []
{
new DelegateDestructuringPolicy()
})
.ToArray();
}
public LogEventProperty CreateProperty(string name, object value, bool destructureObjects = false)
{
return new LogEventProperty(name, CreatePropertyValue(value, destructureObjects));
}
public LogEventPropertyValue CreatePropertyValue(object value, bool destructureObjects = false)
{
return CreatePropertyValue(value, destructureObjects, 1);
}
public LogEventPropertyValue CreatePropertyValue(object value, Destructuring destructuring)
{
return CreatePropertyValue(value, destructuring, 1);
}
LogEventPropertyValue CreatePropertyValue(object value, bool destructureObjects, int depth)
{
return CreatePropertyValue(
value,
destructureObjects ?
Destructuring.Destructure :
Destructuring.Default,
depth);
}
LogEventPropertyValue CreatePropertyValue(object value, Destructuring destructuring, int depth)
{
if (value == null)
return new ScalarValue(null);
if (destructuring == Destructuring.Stringify)
return new ScalarValue(value.ToString());
var valueType = value.GetType();
var limiter = new DepthLimiter(depth, _maximumDestructuringDepth, this);
foreach (var scalarConversionPolicy in _scalarConversionPolicies)
{
ScalarValue converted;
if (scalarConversionPolicy.TryConvertToScalar(value, limiter, out converted))
return converted;
}
if (destructuring == Destructuring.Destructure)
{
foreach (var destructuringPolicy in _destructuringPolicies)
{
LogEventPropertyValue result;
if (destructuringPolicy.TryDestructure(value, limiter, out result))
return result;
}
}
var enumerable = value as IEnumerable;
if (enumerable != null)
{
// Only dictionaries with 'scalar' keys are permitted, as
// more complex keys may not serialize to unique values for
// representation in sinks. This check strengthens the expectation
// that resulting dictionary is representable in JSON as well
// as richer formats (e.g. XML, .NET type-aware...).
// Only actual dictionaries are supported, as arbitrary types
// can implement multiple IDictionary interfaces and thus introduce
// multiple different interpretations.
if (IsValueTypeDictionary(valueType))
{
return new DictionaryValue(enumerable.Cast<dynamic>()
.Select(kvp => new KeyValuePair<ScalarValue, LogEventPropertyValue>(
(ScalarValue)limiter.CreatePropertyValue(kvp.Key, destructuring),
limiter.CreatePropertyValue(kvp.Value, destructuring)))
.Where(kvp => kvp.Key.Value != null));
}
return
new SequenceValue(
enumerable.Cast<object>().Select(o => limiter.CreatePropertyValue(o, destructuring)));
}
if (destructuring == Destructuring.Destructure)
{
var typeTag = value.GetType().Name;
if (typeTag.Length <= 0 || !char.IsLetter(typeTag[0]))
typeTag = null;
return new StructureValue(GetProperties(value, limiter), typeTag);
}
return new ScalarValue(value.ToString());
}
bool IsValueTypeDictionary(Type valueType)
{
return valueType.IsGenericType &&
valueType.GetGenericTypeDefinition() == typeof(Dictionary<,>) &&
IsValidDictionaryKeyType(valueType.GetGenericArguments()[0]);
}
bool IsValidDictionaryKeyType(Type valueType)
{
return BuiltInScalarTypes.Contains(valueType) || valueType.IsEnum;
}
static IEnumerable<LogEventProperty> GetProperties(object value, ILogEventPropertyValueFactory recursive)
{
var valueType = value.GetType();
var props = valueType.GetProperties().Where(p => p.CanRead &&
p.GetGetMethod().IsPublic &&
!p.GetGetMethod().IsStatic &&
(p.Name != "Item" || p.GetIndexParameters().Length == 0));
foreach (var prop in props)
{
object propValue;
try
{
propValue = prop.GetValue(value, null);
}
catch (TargetParameterCountException)
{
SelfLog.WriteLine("The property accessor {0} is a non-default indexer", prop);
continue;
}
catch (TargetInvocationException ex)
{
SelfLog.WriteLine("The property accessor {0} threw exception {1}", prop, ex);
propValue = "The property accessor threw an exception: " + ex.InnerException.GetType().Name;
}
yield return new LogEventProperty(prop.Name, recursive.CreatePropertyValue(propValue, true));
}
}
}
}