Skip to content

Commit

Permalink
Event enrichers by settings uses extension methods
Browse files Browse the repository at this point in the history
Keeps syntax in settings the same as if using config object and uses
established extension methods as entry points rather than directly
activating the enrichers.
  • Loading branch information
johncrn committed Jan 16, 2016
1 parent 885b269 commit e35d82b
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 44 deletions.
54 changes: 26 additions & 28 deletions src/Serilog/Settings/KeyValuePairs/KeyValuePairSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,11 @@ class KeyValuePairSettings : ILoggerSettings
const string UsingDirective = "using";
const string WriteToDirective = "write-to";
const string MinimumLevelDirective = "minimum-level";
const string EnrichWithDirective = "enrich:with";
const string EnrichWithDirective = "enrich";
const string EnrichWithPropertyDirective = "enrich:with-property";

const string UsingDirectiveFullFormPrefix = "using:";
const string EnrichWithEventEnricherPrefix = "enrich:with:";
const string EnrichWithEventEnricherPrefix = "enrich:";
const string EnrichWithPropertyDirectivePrefix = "enrich:with-property:";

const string WriteToDirectiveRegex = @"^write-to:(?<method>[A-Za-z0-9]*)(\.(?<argument>[A-Za-z0-9]*)){0,1}$";
Expand Down Expand Up @@ -82,11 +82,8 @@ public void Configure(LoggerConfiguration loggerConfiguration)
}

var eventEnricherDirectives = directives.Where(dir =>
dir.Key.StartsWith(EnrichWithEventEnricherPrefix) && dir.Key.Length > EnrichWithEventEnricherPrefix.Length)
.Select(dir => {
var enricherName = dir.Key.Substring(EnrichWithEventEnricherPrefix.Length);
return !enricherName.EndsWith("Enricher") ? String.Format("{0}Enricher", enricherName) : enricherName;
});
dir.Key.StartsWith(EnrichWithEventEnricherPrefix) && !dir.Key.StartsWith(EnrichWithPropertyDirectivePrefix) && dir.Key.Length > EnrichWithEventEnricherPrefix.Length)
.Select(dir => dir.Key.Substring(EnrichWithEventEnricherPrefix.Length));

var splitWriteTo = new Regex(WriteToDirectiveRegex);

Expand All @@ -107,22 +104,27 @@ where splitWriteTo.IsMatch(wt.Key)

if (eventEnricherDirectives.Any())
{
var eventEnricherTypes = FindEventEnrichers(configurationAssemblies);
var eventEnricherTypes = FindEventEnricherConfigurationMethods(configurationAssemblies);

foreach(var eventEnricherDirective in eventEnricherDirectives)
{
var target = eventEnricherTypes
.Where(e => e.AsType().Name == eventEnricherDirective)
.Where(e => e.Name == eventEnricherDirective &&
e.GetParameters().Skip(1).All(p =>
#if NET40
(p.Attributes & ParameterAttributes.HasDefault) != ParameterAttributes.None
#else
p.HasDefaultValue
#endif
))
.OrderByDescending(m => m.GetParameters().Length)
.FirstOrDefault();

if (target != null)
{
var instansiatedTarget = Activator.CreateInstance(target.AsType()) as Core.ILogEventEnricher;
loggerConfiguration.Enrich.With(instansiatedTarget);
target.Invoke(null, new object[] { loggerConfiguration.Enrich });
}
}

//eventEnricherDirectives
}

if (sinkDirectives.Any())
Expand Down Expand Up @@ -204,6 +206,16 @@ internal static object ConvertToType(string value, Type toType)
}

internal static IList<MethodInfo> FindSinkConfigurationMethods(IEnumerable<Assembly> configurationAssemblies)
{
return FindConfigurationMethods(configurationAssemblies, typeof(LoggerSinkConfiguration));
}

internal static IList<MethodInfo> FindEventEnricherConfigurationMethods(IEnumerable<Assembly> configurationAssemblies)
{
return FindConfigurationMethods(configurationAssemblies, typeof(LoggerEnrichmentConfiguration));
}

internal static IList<MethodInfo> FindConfigurationMethods(IEnumerable<Assembly> configurationAssemblies, Type configType)
{
return configurationAssemblies
.SelectMany(a => a.
Expand All @@ -215,21 +227,7 @@ internal static IList<MethodInfo> FindSinkConfigurationMethods(IEnumerable<Assem
.Select(t => t.GetTypeInfo()).Where(t => t.IsSealed && t.IsAbstract && !t.IsNested))
.SelectMany(t => t.DeclaredMethods)
.Where(m => m.IsStatic && m.IsPublic && m.IsDefined(typeof(ExtensionAttribute), false))
.Where(m => m.GetParameters()[0].ParameterType == typeof(LoggerSinkConfiguration))
.ToList();
}

internal static IList<TypeInfo> FindEventEnrichers(IEnumerable<Assembly> configurationAssemblies)
{
var logEventEnricherInterface = typeof(Core.ILogEventEnricher).GetTypeInfo();
return configurationAssemblies
.SelectMany(a => a.
#if NET40
GetTypes().Select(t => t.GetTypeInfo())
#else
DefinedTypes
#endif
.Where(t => logEventEnricherInterface.IsAssignableFrom(t) && !t.IsAbstract))
.Where(m => m.GetParameters()[0].ParameterType == configType)
.ToList();
}
}
Expand Down
10 changes: 5 additions & 5 deletions test/Serilog.Tests/Settings/AppSettingsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ public void CustomPrefixCannotBeSerilog()
public void ThreadIdEnricherIsApplied()
{
// Make sure we have the expected key in the App.config
Assert.NotNull(ConfigurationManager.AppSettings["serilog:enrich:with:ThreadId"]);
Assert.NotNull(ConfigurationManager.AppSettings["serilog:enrich:WithThreadId"]);

LogEvent evt = null;
var log = new LoggerConfiguration()
Expand All @@ -93,7 +93,7 @@ public void ThreadIdEnricherIsApplied()
public void MachineNameEnricherIsApplied()
{
// Make sure we have the expected key in the App.config
Assert.NotNull(ConfigurationManager.AppSettings["serilog:enrich:with:MachineName"]);
Assert.NotNull(ConfigurationManager.AppSettings["serilog:enrich:WithMachineName"]);

LogEvent evt = null;
var log = new LoggerConfiguration()
Expand All @@ -112,7 +112,7 @@ public void MachineNameEnricherIsApplied()
public void EnrivonmentUserNameEnricherIsApplied()
{
// Make sure we have the expected key in the App.config
Assert.NotNull(ConfigurationManager.AppSettings["serilog:enrich:with:EnvironmentUserName"]);
Assert.NotNull(ConfigurationManager.AppSettings["serilog:enrich:WithEnvironmentUserName"]);

LogEvent evt = null;
var log = new LoggerConfiguration()
Expand All @@ -133,7 +133,7 @@ public void EnrivonmentUserNameEnricherIsApplied()
public void ProcessIdEnricherIsApplied()
{
// Make sure we have the expected key in the App.config
Assert.NotNull(ConfigurationManager.AppSettings["serilog:enrich:with:ProcessId"]);
Assert.NotNull(ConfigurationManager.AppSettings["serilog:enrich:WithProcessId"]);

LogEvent evt = null;
var log = new LoggerConfiguration()
Expand All @@ -154,7 +154,7 @@ public void ProcessIdEnricherIsApplied()
public void LogContextEnricherIsApplied()
{
// Make sure we have the expected key in the App.config
Assert.NotNull(ConfigurationManager.AppSettings["serilog:enrich:with:LogContext"]);
Assert.NotNull(ConfigurationManager.AppSettings["serilog:enrich:FromLogContext"]);

LogEvent evt = null;
var log = new LoggerConfiguration()
Expand Down
12 changes: 6 additions & 6 deletions test/Serilog.Tests/Settings/KeyValuePairSettingsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ public void FindsConfigurationMethodsWithinAnAssembly()
public void FindsEventEnrichersWithinAnAssembly()
{
var eventEnrichers = KeyValuePairSettings
.FindEventEnrichers(new[] { typeof(RollingFileSink)
.FindEventEnricherConfigurationMethods(new[] { typeof(RollingFileSink)
#if DNXCORE50
.GetTypeInfo()
#endif
Expand All @@ -96,16 +96,16 @@ public void FindsEventEnrichersWithinAnAssembly()


#if LOGCONTEXT
Assert.True(eventEnrichers.Contains("LogContextEnricher"));
Assert.True(eventEnrichers.Contains("FromLogContext"));
#endif
#if !DOTNET5_1
Assert.True(eventEnrichers.Contains("EnvironmentUserNameEnricher"));
Assert.True(eventEnrichers.Contains("MachineNameEnricher"));
Assert.True(eventEnrichers.Contains("WithEnvironmentUserName"));
Assert.True(eventEnrichers.Contains("WithMachineName"));
#endif
#if PROCESS
Assert.True(eventEnrichers.Contains("ProcessIdEnricher"));
Assert.True(eventEnrichers.Contains("WithProcessId"));
#endif
Assert.True(eventEnrichers.Contains("ThreadIdEnricher"));
Assert.True(eventEnrichers.Contains("WithThreadId"));
}

[Fact]
Expand Down
10 changes: 5 additions & 5 deletions test/Serilog.Tests/app.config
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@
<add key="serilog:enrich:with-property:Path" value="%PATH%" />
<add key="custom1:serilog:minimum-level" value="Warning" />
<add key="custom2:serilog:minimum-level" value="Error" />
<add key="serilog:enrich:with:ThreadId"/>
<add key="serilog:enrich:with:MachineName"/>
<add key="serilog:enrich:with:ProcessId"/>
<add key="serilog:enrich:with:EnvironmentUserName"/>
<add key="serilog:enrich:with:LogContext"/>
<add key="serilog:enrich:WithThreadId"/>
<add key="serilog:enrich:WithMachineName"/>
<add key="serilog:enrich:WithProcessId"/>
<add key="serilog:enrich:WithEnvironmentUserName"/>
<add key="serilog:enrich:FromLogContext"/>
</appSettings>
</configuration>

0 comments on commit e35d82b

Please sign in to comment.