-
Notifications
You must be signed in to change notification settings - Fork 458
/
Copy pathLoggingFacility.cs
458 lines (409 loc) · 15 KB
/
LoggingFacility.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
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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
// Copyright 2004-2017 Castle Project - http://www.castleproject.org/
//
// 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.
#pragma warning disable CS0618 // Suppress LoggerImplementation is obsolete warning until removed
namespace Castle.Facilities.Logging
{
using System;
using System.Diagnostics;
using System.Reflection;
using Castle.Core.Internal;
using Castle.Core.Logging;
using Castle.MicroKernel;
using Castle.MicroKernel.Facilities;
using Castle.MicroKernel.Registration;
using Castle.MicroKernel.SubSystems.Conversion;
/// <summary>
/// A facility for logging support.
/// </summary>
public class LoggingFacility : AbstractFacility
{
#if CASTLE_SERVICES_LOGGING //Castle.Services.Logging.Log4netIntegration and Castle.Services.Logging.NLogIntegration are not available for .NET Standard
private static readonly String ExtendedLog4NetLoggerFactoryTypeName =
"Castle.Services.Logging.Log4netIntegration.ExtendedLog4netFactory," +
"Castle.Services.Logging.Log4netIntegration,Version=4.0.0.0, Culture=neutral," +
"PublicKeyToken=407dd0808d44fbdc";
private static readonly String ExtendedNLogLoggerFactoryTypeName =
"Castle.Services.Logging.NLogIntegration.ExtendedNLogFactory," +
"Castle.Services.Logging.NLogIntegration,Version=4.0.0.0, Culture=neutral," +
"PublicKeyToken=407dd0808d44fbdc";
private static readonly String Log4NetLoggerFactoryTypeName =
"Castle.Services.Logging.Log4netIntegration.Log4netFactory," +
"Castle.Services.Logging.Log4netIntegration,Version=4.0.0.0, Culture=neutral," +
"PublicKeyToken=407dd0808d44fbdc";
private static readonly String NLogLoggerFactoryTypeName =
"Castle.Services.Logging.NLogIntegration.NLogFactory," +
"Castle.Services.Logging.NLogIntegration,Version=4.0.0.0, Culture=neutral," +
"PublicKeyToken=407dd0808d44fbdc";
#endif
private readonly string customLoggerFactoryTypeName;
private string configFileName;
private ITypeConverter converter;
private LoggerImplementation? loggerImplementation;
private Type loggingFactoryType;
private LoggerLevel? loggerLevel;
private ILoggerFactory loggerFactory;
private string logName;
private bool configuredExternally;
/// <summary>
/// Initializes a new instance of the <see cref="LoggingFacility" /> class.
/// </summary>
public LoggingFacility()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="LoggingFacility" /> class.
/// </summary>
/// <param name="loggingApi"> The LoggerImplementation that should be used </param>
[Obsolete("A logger factory implementation type should be provided via LogUsing<T>(), this will be removed in the future.")]
public LoggingFacility(LoggerImplementation loggingApi) : this(loggingApi, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="LoggingFacility" /> class.
/// </summary>
/// <param name="loggingApi"> The LoggerImplementation that should be used </param>
/// <param name="configFile"> The configuration file that should be used by the chosen LoggerImplementation </param>
[Obsolete("A logger factory implementation type should be provided via LogUsing<T>(), this will be removed in the future.")]
public LoggingFacility(LoggerImplementation loggingApi, string configFile) : this(loggingApi, null, configFile)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="LoggingFacility" /> class using a custom LoggerImplementation
/// </summary>
/// <param name="configFile"> The configuration file that should be used by the chosen LoggerImplementation </param>
/// <param name="customLoggerFactory"> The type name of the type of the custom logger factory. </param>
public LoggingFacility(string customLoggerFactory, string configFile)
: this(LoggerImplementation.Custom, customLoggerFactory, configFile)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="LoggingFacility" /> class.
/// </summary>
/// <param name="loggingApi"> The LoggerImplementation that should be used </param>
/// <param name="configFile"> The configuration file that should be used by the chosen LoggerImplementation </param>
/// <param name="customLoggerFactory"> The type name of the type of the custom logger factory. (only used when loggingApi is set to LoggerImplementation.Custom) </param>
[Obsolete("A logger factory implementation type should be provided via LogUsing<T>(), this will be removed in the future.")]
public LoggingFacility(LoggerImplementation loggingApi, string customLoggerFactory, string configFile)
{
loggerImplementation = loggingApi;
customLoggerFactoryTypeName = customLoggerFactory;
configFileName = configFile;
}
[Obsolete("A logger factory implementation type should be provided via LogUsing<T>(), this will be removed in the future.")]
public LoggingFacility LogUsing(LoggerImplementation loggingApi)
{
if (loggingApi == LoggerImplementation.Custom)
{
throw new FacilityException("To use custom logger use LogUsing<TLoggerFactory>() method.");
}
loggerImplementation = loggingApi;
return this;
}
public LoggingFacility LogUsing<TLoggerFactory>()
where TLoggerFactory : ILoggerFactory
{
loggerImplementation = LoggerImplementation.Custom;
loggingFactoryType = typeof(TLoggerFactory);
return this;
}
public LoggingFacility LogUsing<TLoggerFactory>(TLoggerFactory loggerFactory)
where TLoggerFactory : ILoggerFactory
{
loggerImplementation = LoggerImplementation.Custom;
loggingFactoryType = typeof(TLoggerFactory);
this.loggerFactory = loggerFactory;
return this;
}
public LoggingFacility ConfiguredExternally()
{
configuredExternally = true;
return this;
}
public LoggingFacility WithConfig(string configFile)
{
if (configFile == null) throw new ArgumentNullException(nameof(configFile));
configFileName = configFile;
return this;
}
public LoggingFacility WithLevel(LoggerLevel level)
{
loggerLevel = level;
return this;
}
public LoggingFacility ToLog(string name)
{
logName = name;
return this;
}
#if CASTLE_SERVICES_LOGGING
[Obsolete("A logger factory implementation type should be provided via LogUsing<T>(), this will be removed in the future.")]
public LoggingFacility UseLog4Net()
{
return LogUsing(LoggerImplementation.Log4net);
}
[Obsolete("A logger factory implementation type should be provided via LogUsing<T>(), this will be removed in the future.")]
public LoggingFacility UseLog4Net(string configFile)
{
return UseLog4Net().WithConfig(configFile);
}
[Obsolete("A logger factory implementation type should be provided via LogUsing<T>(), this will be removed in the future.")]
public LoggingFacility UseNLog()
{
return LogUsing(LoggerImplementation.NLog);
}
[Obsolete("A logger factory implementation type should be provided via LogUsing<T>(), this will be removed in the future.")]
public LoggingFacility UseNLog(string configFile)
{
return LogUsing(LoggerImplementation.NLog).WithConfig(configFile);
}
#endif
#if FEATURE_SYSTEM_CONFIGURATION
/// <summary>
/// loads configuration from current AppDomain's config file (aka web.config/app.config)
/// </summary>
/// <returns> </returns>
public LoggingFacility WithAppConfig()
{
configFileName = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
return this;
}
#endif
protected override void Init()
{
SetUpTypeConverter();
if (loggerFactory == null)
{
loggerFactory = ReadConfigurationAndCreateLoggerFactory();
}
RegisterLoggerFactory(loggerFactory);
RegisterDefaultILogger(loggerFactory);
RegisterSubResolver(loggerFactory);
}
private ILoggerFactory CreateProperLoggerFactory(LoggerImplementation loggerApi)
{
var loggerFactoryType = GetLoggingFactoryType(loggerApi);
Debug.Assert(loggerFactoryType != null, "loggerFactoryType != null");
var ctorArgs = GetLoggingFactoryArguments(loggerFactoryType);
return loggerFactoryType.CreateInstance<ILoggerFactory>(ctorArgs);
}
private Type EnsureIsValidLoggerFactoryType(Type loggerFactoryType)
{
if (loggerFactoryType.Is<ILoggerFactory>() || loggerFactoryType.Is<IExtendedLoggerFactory>())
{
return loggerFactoryType;
}
throw new FacilityException("The specified type '" + loggerFactoryType +
"' does not implement either ILoggerFactory or IExtendedLoggerFactory.");
}
private string GetConfigFile()
{
if (configFileName != null)
{
return configFileName;
}
if (FacilityConfig != null)
{
return FacilityConfig.Attributes["configFile"];
}
return null;
}
private Type GetCustomLoggerType()
{
return EnsureIsValidLoggerFactoryType(ReadCustomLoggerType());
}
private object[] GetLoggingFactoryArguments(Type loggerFactoryType)
{
const BindingFlags flags = BindingFlags.Instance | BindingFlags.Public;
ConstructorInfo ctor;
if (IsConfiguredExternally())
{
ctor = loggerFactoryType.GetConstructor(flags, null, new[] { typeof(bool) }, null);
if (ctor != null)
{
return new object[] { true };
}
}
var configFile = GetConfigFile();
if (configFile != null)
{
ctor = loggerFactoryType.GetConstructor(flags, null, new[] { typeof(string) }, null);
if (ctor != null)
{
return new object[] { configFile };
}
}
var level = GetLoggingLevel();
if (level != null)
{
ctor = loggerFactoryType.GetConstructor(flags, null, new[] { typeof(LoggerLevel) }, null);
if (ctor != null)
{
return new object[] { level.Value };
}
}
ctor = loggerFactoryType.GetConstructor(flags, null, Type.EmptyTypes, null);
if (ctor != null)
{
return new object[0];
}
throw new FacilityException("No support constructor found for logging type " + loggerFactoryType);
}
private bool IsConfiguredExternally()
{
if (configuredExternally)
{
return true;
}
if (FacilityConfig != null)
{
var value = FacilityConfig.Attributes["configuredExternally"];
if (value != null)
{
return converter.PerformConversion<bool>(value);
}
}
return false;
}
private LoggerLevel? GetLoggingLevel()
{
if (loggerLevel.HasValue)
{
return loggerLevel;
}
if (FacilityConfig != null)
{
var level = FacilityConfig.Attributes["loggerLevel"];
if (level != null)
{
return converter.PerformConversion<LoggerLevel>(level);
}
}
return null;
}
private Type GetLoggingFactoryType(LoggerImplementation loggerApi)
{
switch (loggerApi)
{
case LoggerImplementation.Custom:
return GetCustomLoggerType();
case LoggerImplementation.Null:
return typeof(NullLogFactory);
case LoggerImplementation.Console:
return typeof(ConsoleFactory);
#if FEATURE_EVENTLOG //has dependency on Castle.Core.Logging.DiagnosticsLoggerFactory
case LoggerImplementation.Diagnostics:
return typeof(DiagnosticsLoggerFactory);
#endif
case LoggerImplementation.Trace:
return typeof(TraceLoggerFactory);
#if CASTLE_SERVICES_LOGGING
case LoggerImplementation.NLog:
return converter.PerformConversion<Type>(NLogLoggerFactoryTypeName);
case LoggerImplementation.Log4net:
return converter.PerformConversion<Type>(Log4NetLoggerFactoryTypeName);
case LoggerImplementation.ExtendedLog4net:
return converter.PerformConversion<Type>(ExtendedLog4NetLoggerFactoryTypeName);
case LoggerImplementation.ExtendedNLog:
return converter.PerformConversion<Type>(ExtendedNLogLoggerFactoryTypeName);
#endif
default:
{
throw new FacilityException("An invalid loggingApi was specified: " + loggerApi);
}
}
}
private ILoggerFactory ReadConfigurationAndCreateLoggerFactory()
{
var logApi = ReadLoggingApi();
var loggerFactory = CreateProperLoggerFactory(logApi);
return loggerFactory;
}
private Type ReadCustomLoggerType()
{
if (FacilityConfig != null)
{
var customLoggerType = FacilityConfig.Attributes["customLoggerFactory"];
if (string.IsNullOrEmpty(customLoggerType) == false)
{
return converter.PerformConversion<Type>(customLoggerType);
}
}
if (customLoggerFactoryTypeName != null)
{
return converter.PerformConversion<Type>(customLoggerFactoryTypeName);
}
if (loggingFactoryType != null)
{
return loggingFactoryType;
}
var message = "If you specify loggingApi='custom' " +
"then you must use the attribute customLoggerFactory to inform the " +
"type name of the custom logger factory";
throw new FacilityException(message);
}
private LoggerImplementation ReadLoggingApi()
{
if (FacilityConfig != null)
{
var configLoggingApi = FacilityConfig.Attributes["loggingApi"];
if (string.IsNullOrEmpty(configLoggingApi) == false)
{
return converter.PerformConversion<LoggerImplementation>(configLoggingApi);
}
}
return loggerImplementation.GetValueOrDefault(LoggerImplementation.Console);
}
private void RegisterDefaultILogger(ILoggerFactory factory)
{
if (factory is IExtendedLoggerFactory)
{
var defaultLogger = ((IExtendedLoggerFactory) factory).Create(logName ?? "Default");
Kernel.Register(Component.For<IExtendedLogger>().NamedAutomatically("ilogger.default").Instance(defaultLogger),
Component.For<ILogger>().NamedAutomatically("ilogger.default.base").Instance(defaultLogger));
}
else
{
Kernel.Register(Component.For<ILogger>().NamedAutomatically("ilogger.default").Instance(factory.Create(logName ?? "Default")));
}
}
private void RegisterLoggerFactory(ILoggerFactory factory)
{
if (factory is IExtendedLoggerFactory)
{
Kernel.Register(
Component.For<IExtendedLoggerFactory>().NamedAutomatically("iloggerfactory").Instance((IExtendedLoggerFactory) factory),
Component.For<ILoggerFactory>().NamedAutomatically("iloggerfactory.base").Instance(factory));
}
else
{
Kernel.Register(Component.For<ILoggerFactory>().NamedAutomatically("iloggerfactory").Instance(factory));
}
}
private void RegisterSubResolver(ILoggerFactory loggerFactory)
{
var extendedLoggerFactory = loggerFactory as IExtendedLoggerFactory;
if (extendedLoggerFactory == null)
{
Kernel.Resolver.AddSubResolver(new LoggerResolver(loggerFactory, logName));
return;
}
Kernel.Resolver.AddSubResolver(new LoggerResolver(extendedLoggerFactory, logName));
}
private void SetUpTypeConverter()
{
converter = Kernel.GetSubSystem(SubSystemConstants.ConversionManagerKey) as IConversionManager;
}
}
}
#pragma warning restore CS0618 // Suppress LoggerImplementation is obsolete warning until removed