Repository navigation
Expand file tree
/
Copy pathLog4NetProvider.cs
More file actions
367 lines (328 loc) · 13.5 KB
/
Copy pathLog4NetProvider.cs
File metadata and controls
367 lines (328 loc) · 13.5 KB
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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
using log4net;
using log4net.Config;
using log4net.Repository;
using Microsoft.Extensions.Logging.Log4Net.AspNetCore.Entities;
using Microsoft.Extensions.Logging.Log4Net.AspNetCore.Extensions;
using Microsoft.Extensions.Logging.Log4Net.AspNetCore.Scope;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
namespace Microsoft.Extensions.Logging
{
/// <summary>
/// The log4net provider class.
/// </summary>
/// <seealso cref="ILoggerProvider" />
public class Log4NetProvider : ILoggerProvider, ISupportExternalScope
{
/// <summary>
/// The loggers collection.
/// </summary>
private readonly ConcurrentDictionary<string, Log4NetLogger> loggers = new ConcurrentDictionary<string, Log4NetLogger>();
/// <summary>
/// Prevents to dispose the object more than single time.
/// </summary>
private bool disposedValue = false;
/// <summary>
/// The log4net repository.
/// </summary>
private ILoggerRepository loggerRepository;
/// <summary>
/// The provider options.
/// </summary>
private Log4NetProviderOptions options;
/// <summary>
/// The external logging scope provider.
/// </summary>
/// <remarks>
/// Reading the offical logging implementations, it seems like we need to handle the case that this might never be set.
/// We handle it with a NullScopeProvider instead of null checks, to make the process of implementing interfaces like
/// <see cref="ILog4NetLoggingEventFactory"/> less error prone for consumers.
/// </remarks>
public IExternalScopeProvider ExternalScopeProvider { get; private set; } = NullScopeProvider.Instance;
/// <summary>
/// Initializes a new instance of the <see cref="Log4NetProvider"/> class.
/// </summary>
public Log4NetProvider()
: this(new Log4NetProviderOptions())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Log4NetProvider"/> class.
/// </summary>
/// <param name="log4NetConfigFileName">The log4NetConfigFile.</param>
public Log4NetProvider(string log4NetConfigFileName)
: this(new Log4NetProviderOptions(log4NetConfigFileName))
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Log4NetProvider"/> class.
/// </summary>
/// <param name="options">The options.</param>
/// <exception cref="ArgumentNullException">options</exception>
/// <exception cref="NotSupportedException">Wach cannot be true when you are overwriting config file values with values from configuration section.</exception>
public Log4NetProvider(Log4NetProviderOptions options)
{
this.SetOptionsIfValid(options);
Assembly loggingAssembly = this.GetLoggingReferenceAssembly();
this.CreateLoggerRepository(loggingAssembly);
this.ConfigureLog4NetLibrary();
}
/// <summary>
/// Finalizes the instance of the <see cref="Log4NetProvider"/> object.
/// </summary>
~Log4NetProvider()
{
Dispose(false);
}
/// <summary>
/// Creates the logger.
/// </summary>
/// <returns>An instance of the <see cref="ILogger"/>.</returns>
public ILogger CreateLogger()
=> this.CreateLogger(this.options.Name);
/// <summary>
/// Creates the logger.
/// </summary>
/// <param name="categoryName">The category name.</param>
/// <returns>An instance of the <see cref="ILogger"/>.</returns>
public ILogger CreateLogger(string categoryName)
=> this.loggers.GetOrAdd(categoryName, this.CreateLoggerImplementation);
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
this.loggerRepository.Shutdown();
this.loggers.Clear();
}
disposedValue = true;
}
}
/// <summary>
/// Updates configuration nodes overriding values if required.
/// </summary>
/// <param name="configXmlDocument">The configuration file XML document.</param>
/// <param name="overridingNodes">The overriding values available</param>
/// <returns>An <see cref="XmlDocument"/> within the overriding values replaced.</returns>
private static XmlDocument UpdateNodesWithOverridingValues(XmlDocument configXmlDocument, IEnumerable<NodeInfo> overridingNodes)
{
var additionalConfig = overridingNodes;
if (additionalConfig != null)
{
var configXDoc = configXmlDocument.ToXDocument();
foreach (var nodeInfo in additionalConfig)
{
var node = configXDoc.XPathSelectElement(nodeInfo.XPath);
if (node != null)
{
if (nodeInfo.NodeContent != null)
{
node.Value = nodeInfo.NodeContent;
}
AddOrUpdateAttributes(node, nodeInfo);
}
}
return configXDoc.ToXmlDocument();
}
return configXmlDocument;
}
/// <summary>
/// Adds or updates the attributes specified in the node information.
/// </summary>
/// <param name="node">The node.</param>
/// <param name="nodeInfo">The node information.</param>
private static void AddOrUpdateAttributes(XElement node, NodeInfo nodeInfo)
{
if (nodeInfo?.Attributes != null)
{
foreach (var attribute in nodeInfo.Attributes)
{
var nodeAttribute = node.Attributes()
.FirstOrDefault(a => a.Name.LocalName.Equals(attribute.Key, StringComparison.OrdinalIgnoreCase));
if (nodeAttribute != null)
{
nodeAttribute.Value = attribute.Value;
}
else
{
node.SetAttributeValue(attribute.Key, attribute.Value);
}
}
}
}
/// <summary>
/// Parses log4net config file.
/// </summary>
/// <param name="filename">The filename.</param>
/// <returns>The <see cref="XmlElement"/> with the log4net XML element.</returns>
private static XmlDocument ParseLog4NetConfigFile(string filename)
{
using (FileStream stream = File.OpenRead(filename))
{
var settings = new XmlReaderSettings
{
DtdProcessing = DtdProcessing.Prohibit
};
var log4netConfig = new XmlDocument();
using (var reader = XmlReader.Create(stream, settings))
{
log4netConfig.Load(reader);
}
return log4netConfig;
}
}
/// <summary>
/// Creates the logger implementation.
/// </summary>
/// <param name="name">The name.</param>
/// <returns>The <see cref="Log4NetLogger"/> instance.</returns>
private Log4NetLogger CreateLoggerImplementation(string name)
{
var loggerOptions = new Log4NetProviderOptions
{
Name = name,
LoggerRepository = this.loggerRepository.Name,
OverrideCriticalLevelWith = this.options.OverrideCriticalLevelWith,
LoggingEventFactory = this.options.LoggingEventFactory ?? new Log4NetLoggingEventFactory(),
LogLevelTranslator = this.options.LogLevelTranslator ?? new Log4NetLogLevelTranslator(),
};
return new Log4NetLogger(loggerOptions, ExternalScopeProvider);
}
/// <summary>
/// Gets the current executing assembly considering the target framework.
/// </summary>
/// <returns>The assembly to be used as the reference logging assembly.</returns>
private Assembly GetLoggingReferenceAssembly()
{
return this.options.ConfigurationAssembly ?? Assembly.GetExecutingAssembly();
}
/// <summary>
/// Ensures that provided options combinations are valid, and sets the class field if everything is ok.
/// </summary>
/// <param name="options">The options to validate.</param>
/// <exception cref="NotSupportedException">
/// Throws when the Watch option is set and there are properties to override.
/// </exception>
/// <exception cref="ArgumentNullException">
/// Throws when the options parameter is null.
/// </exception>
private void SetOptionsIfValid(Log4NetProviderOptions options)
{
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
if (options.Watch
&& options.PropertyOverrides.Any())
{
throw new NotSupportedException("Wach cannot be true when you are overwriting config file values with values from configuration section.");
}
this.options = options;
}
/// <summary>
/// Configures the log4net library using the available configuration data.
/// </summary>
private void ConfigureLog4NetLibrary()
{
if (this.options.UseWebOrAppConfig)
{
XmlConfigurator.Configure(this.loggerRepository);
return;
}
if (!this.options.ExternalConfigurationSetup)
{
string fileNamePath = CreateLog4NetFilePath();
if (this.options.Watch)
{
XmlConfigurator.ConfigureAndWatch(
this.loggerRepository,
new FileInfo(fileNamePath));
}
else
{
var configXml = ParseLog4NetConfigFile(fileNamePath);
if (this.options.PropertyOverrides != null
&& this.options.PropertyOverrides.Any())
{
configXml = UpdateNodesWithOverridingValues(
configXml,
this.options.PropertyOverrides);
}
XmlConfigurator.Configure(this.loggerRepository, configXml.DocumentElement);
}
}
}
/// <summary>
/// Creates the log4net.config file path.
/// </summary>
/// <returns>The full path to the log4net.config file.</returns>
private string CreateLog4NetFilePath()
{
string fileNamePath = this.options.Log4NetConfigFileName;
if (!Path.IsPathRooted(fileNamePath))
{
fileNamePath = Path.Combine(AppContext.BaseDirectory, fileNamePath);
}
return Path.GetFullPath(fileNamePath);
}
/// <summary>
/// Gets or creates the logger repository using the given assembly.
/// </summary>
/// <param name="assembly">The assembly to be used to create the repository.</param>
private void CreateLoggerRepository(Assembly assembly)
{
Type repositoryType = typeof(log4net.Repository.Hierarchy.Hierarchy);
if (!string.IsNullOrEmpty(this.options.LoggerRepository))
{
try
{
this.loggerRepository = LogManager.GetRepository(this.options.LoggerRepository);
if (this.options.ExternalConfigurationSetup)
{
// The logger repository is already configured. We can exit here.
return;
}
}
catch (log4net.Core.LogException)
{
// The logger repository is not defined outside the extension.
this.loggerRepository = null;
}
if (this.loggerRepository == null)
{
this.loggerRepository =
LogManager.CreateRepository(this.options.LoggerRepository, repositoryType);
}
}
else
{
this.loggerRepository =
LogManager.CreateRepository(assembly, repositoryType);
}
}
public void SetScopeProvider(IExternalScopeProvider scopeProvider)
{
ExternalScopeProvider = scopeProvider;
}
}
}