Skip to content

Commit 06f8c11

Browse files
author
Sergey Komisarchik
authored
Merge pull request #221 from skomis-mm/conditionalEnrich
Support conditional/leveled enrichers from Serilog 2.9+
2 parents 543d858 + e12105f commit 06f8c11

File tree

8 files changed

+77
-29
lines changed

8 files changed

+77
-29
lines changed

sample/Sample/Program.cs

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,24 @@
11
using System;
22

3-
using Microsoft.Extensions.Configuration;
4-
using Serilog;
53
using System.IO;
64
using System.Linq;
5+
using System.Collections.Generic;
6+
using System.Threading;
7+
8+
using Microsoft.Extensions.Configuration;
9+
10+
using Serilog;
711
using Serilog.Core;
812
using Serilog.Events;
9-
using System.Collections.Generic;
1013

1114
namespace Sample
1215
{
1316
public class Program
1417
{
1518
public static void Main(string[] args)
1619
{
20+
Thread.CurrentThread.Name = "Main thread";
21+
1722
var configuration = new ConfigurationBuilder()
1823
.SetBasePath(Directory.GetCurrentDirectory())
1924
.AddJsonFile(path: "appsettings.json", optional: false, reloadOnChange: true)
@@ -47,7 +52,7 @@ public static void Main(string[] args)
4752

4853
Console.WriteLine("\nPress \"q\" to quit, or any other key to run again.\n");
4954
}
50-
while(!args.Contains("--run-once") && (Console.ReadKey().KeyChar != 'q'));
55+
while (!args.Contains("--run-once") && (Console.ReadKey().KeyChar != 'q'));
5156
}
5257
}
5358

@@ -73,7 +78,7 @@ public bool TryDestructure(object value, ILogEventPropertyValueFactory propertyV
7378
{
7479
result = null;
7580

76-
if(value is LoginData)
81+
if (value is LoginData)
7782
{
7883
result = new StructureValue(
7984
new List<LogEventProperty>

sample/Sample/Sample.csproj

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,12 +22,12 @@
2222
</ItemGroup>
2323

2424
<ItemGroup>
25-
<PackageReference Include="Serilog.Sinks.Async" Version="1.0.1" />
25+
<PackageReference Include="Serilog.Sinks.Async" Version="1.4.0" />
2626
<PackageReference Include="Serilog.Sinks.Console" Version="3.1.1" />
27-
<PackageReference Include="Serilog.Sinks.RollingFile" Version="3.0.0" />
28-
<PackageReference Include="Serilog.Enrichers.Environment" Version="2.0.0" />
29-
<PackageReference Include="Serilog.Enrichers.Thread" Version="2.0.0" />
30-
<PackageReference Include="Serilog.Filters.Expressions" Version="1.0.0" />
27+
<PackageReference Include="Serilog.Sinks.File" Version="4.1.0" />
28+
<PackageReference Include="Serilog.Enrichers.Environment" Version="2.1.3" />
29+
<PackageReference Include="Serilog.Enrichers.Thread" Version="3.1.0" />
30+
<PackageReference Include="Serilog.Filters.Expressions" Version="2.1.0" />
3131
</ItemGroup>
3232

3333
<ItemGroup>

sample/Sample/appsettings.json

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,13 +36,44 @@
3636
"Name": "File",
3737
"Args": {
3838
"path": "%TEMP%\\Logs\\serilog-configuration-sample.txt",
39-
"outputTemplate": "{Timestamp:o} [{Level:u3}] ({Application}/{MachineName}/{ThreadId}) {Message}{NewLine}{Exception}"
39+
"outputTemplate": "{Timestamp:o} [{Level:u3}] ({Application}/{MachineName}/{ThreadId}/{ThreadName}) {Message}{NewLine}{Exception}"
4040
}
4141
}
4242
]
4343
}
4444
},
45-
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
45+
"WriteTo:ConditionalSink": {
46+
"Name": "Conditional",
47+
"Args": {
48+
"expression": "@Level in ['Error', 'Fatal']",
49+
"configureSink": [
50+
{
51+
"Name": "File",
52+
"Args": {
53+
"path": "%TEMP%\\Logs\\serilog-configuration-sample-errors.txt"
54+
}
55+
}
56+
]
57+
}
58+
},
59+
"Enrich": [
60+
"FromLogContext",
61+
"WithThreadId",
62+
{
63+
"Name": "AtLevel",
64+
"Args": {
65+
"enrichFromLevel": "Error",
66+
"configureEnricher": [ "WithThreadName" ]
67+
}
68+
},
69+
{
70+
"Name": "When",
71+
"Args": {
72+
"expression": "Application = 'Sample'",
73+
"configureEnricher": [ "WithMachineName" ]
74+
}
75+
}
76+
],
4677
"Properties": {
4778
"Application": "Sample"
4879
},

src/Serilog.Settings.Configuration/Serilog.Settings.Configuration.csproj

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
<PropertyGroup>
44
<Description>Microsoft.Extensions.Configuration (appsettings.json) support for Serilog.</Description>
5-
<VersionPrefix>3.1.1</VersionPrefix>
5+
<VersionPrefix>3.2.0</VersionPrefix>
66
<LangVersion>latest</LangVersion>
77
<Authors>Serilog Contributors</Authors>
88
<TargetFrameworks>netstandard2.0;net451;net461</TargetFrameworks>
@@ -31,7 +31,7 @@
3131
<ItemGroup>
3232
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0" PrivateAssets="All"/>
3333
<PackageReference Include="Microsoft.Extensions.DependencyModel" Version="3.0.0" />
34-
<PackageReference Include="Serilog" Version="2.6.0" />
34+
<PackageReference Include="Serilog" Version="2.9.0" />
3535
<None Include="..\..\assets\icon.png" Pack="true" PackagePath=""/>
3636
</ItemGroup>
3737

src/Serilog.Settings.Configuration/Settings/Configuration/ConfigurationReader.cs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,12 @@ void IConfigurationReader.ApplySinks(LoggerSinkConfiguration loggerSinkConfigura
185185
CallConfigurationMethods(methodCalls, FindSinkConfigurationMethods(_configurationAssemblies), loggerSinkConfiguration);
186186
}
187187

188+
void IConfigurationReader.ApplyEnrichment(LoggerEnrichmentConfiguration loggerEnrichmentConfiguration)
189+
{
190+
var methodCalls = GetMethodCalls(_section);
191+
CallConfigurationMethods(methodCalls, FindEventEnricherConfigurationMethods(_configurationAssemblies), loggerEnrichmentConfiguration);
192+
}
193+
188194
void ApplyEnrichment(LoggerConfiguration loggerConfiguration)
189195
{
190196
var enrichDirective = _section.GetSection("Enrich");
Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
1-
using Serilog.Configuration;
1+
using Serilog.Configuration;
22

33
namespace Serilog.Settings.Configuration
44
{
55
interface IConfigurationReader : ILoggerSettings
66
{
77
void ApplySinks(LoggerSinkConfiguration loggerSinkConfiguration);
8+
void ApplyEnrichment(LoggerEnrichmentConfiguration loggerEnrichmentConfiguration);
89
}
910
}

src/Serilog.Settings.Configuration/Settings/Configuration/ObjectArgumentValue.cs

Lines changed: 11 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
1-
using Microsoft.Extensions.Configuration;
2-
using Serilog.Configuration;
31
using System;
42
using System.Collections.Generic;
53
using System.Linq;
64
using System.Reflection;
75

6+
using Microsoft.Extensions.Configuration;
7+
8+
using Serilog.Configuration;
9+
810
namespace Serilog.Settings.Configuration
911
{
1012
class ObjectArgumentValue : IConfigurationArgumentValue
@@ -31,20 +33,15 @@ public object ConvertTo(Type toType, ResolutionContext resolutionContext)
3133
typeInfo.GetGenericTypeDefinition() is Type genericType && genericType == typeof(Action<>))
3234
{
3335
var configType = typeInfo.GenericTypeArguments[0];
34-
if (configType != typeof(LoggerConfiguration) && configType != typeof(LoggerSinkConfiguration))
35-
throw new ArgumentException($"Configuration for Action<{configType}> is not implemented.");
36-
3736
IConfigurationReader configReader = new ConfigurationReader(_section, _configurationAssemblies, resolutionContext);
3837

39-
if (configType == typeof(LoggerConfiguration))
38+
return configType switch
4039
{
41-
return new Action<LoggerConfiguration>(configReader.Configure);
42-
}
43-
44-
if (configType == typeof(LoggerSinkConfiguration))
45-
{
46-
return new Action<LoggerSinkConfiguration>(loggerSinkConfig => configReader.ApplySinks(loggerSinkConfig));
47-
}
40+
_ when configType == typeof(LoggerConfiguration) => new Action<LoggerConfiguration>(configReader.Configure),
41+
_ when configType == typeof(LoggerSinkConfiguration) => new Action<LoggerSinkConfiguration>(configReader.ApplySinks),
42+
_ when configType == typeof(LoggerEnrichmentConfiguration) => new Action<LoggerEnrichmentConfiguration>(configReader.ApplyEnrichment),
43+
_ => throw new ArgumentException($"Configuration resolution for Action<{configType.Name}> parameter type at the path {_section.Path} is not implemented.")
44+
};
4845
}
4946

5047
if (toType.IsArray)
@@ -97,7 +94,7 @@ bool TryCreateContainer(out object result)
9794
}
9895
}
9996

100-
private static bool IsContainer(Type type, out Type elementType)
97+
static bool IsContainer(Type type, out Type elementType)
10198
{
10299
elementType = null;
103100
foreach (var iface in type.GetInterfaces())

src/Serilog.Settings.Configuration/Settings/Configuration/SurrogateConfigurationMethods.cs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,14 @@ static LoggerConfiguration With(
108108
ILogEventEnricher enricher)
109109
=> loggerEnrichmentConfiguration.With(enricher);
110110

111+
static LoggerConfiguration AtLevel(
112+
LoggerEnrichmentConfiguration loggerEnrichmentConfiguration,
113+
Action<LoggerEnrichmentConfiguration> configureEnricher,
114+
LogEventLevel enrichFromLevel = LevelAlias.Minimum,
115+
LoggingLevelSwitch levelSwitch = null)
116+
=> levelSwitch != null ? loggerEnrichmentConfiguration.AtLevel(levelSwitch, configureEnricher)
117+
: loggerEnrichmentConfiguration.AtLevel(enrichFromLevel, configureEnricher);
118+
111119
static LoggerConfiguration FromLogContext(LoggerEnrichmentConfiguration loggerEnrichmentConfiguration)
112120
=> loggerEnrichmentConfiguration.FromLogContext();
113121

0 commit comments

Comments
 (0)