Skip to content

Commit

Permalink
Merge pull request #221 from skomis-mm/conditionalEnrich
Browse files Browse the repository at this point in the history
Support conditional/leveled enrichers from Serilog 2.9+
  • Loading branch information
Sergey Komisarchik authored May 13, 2020
2 parents 543d858 + e12105f commit 06f8c11
Show file tree
Hide file tree
Showing 8 changed files with 77 additions and 29 deletions.
15 changes: 10 additions & 5 deletions sample/Sample/Program.cs
Original file line number Diff line number Diff line change
@@ -1,19 +1,24 @@
using System;

using Microsoft.Extensions.Configuration;
using Serilog;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Threading;

using Microsoft.Extensions.Configuration;

using Serilog;
using Serilog.Core;
using Serilog.Events;
using System.Collections.Generic;

namespace Sample
{
public class Program
{
public static void Main(string[] args)
{
Thread.CurrentThread.Name = "Main thread";

var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: "appsettings.json", optional: false, reloadOnChange: true)
Expand Down Expand Up @@ -47,7 +52,7 @@ public static void Main(string[] args)

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

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

if(value is LoginData)
if (value is LoginData)
{
result = new StructureValue(
new List<LogEventProperty>
Expand Down
10 changes: 5 additions & 5 deletions sample/Sample/Sample.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,12 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="Serilog.Sinks.Async" Version="1.0.1" />
<PackageReference Include="Serilog.Sinks.Async" Version="1.4.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="3.1.1" />
<PackageReference Include="Serilog.Sinks.RollingFile" Version="3.0.0" />
<PackageReference Include="Serilog.Enrichers.Environment" Version="2.0.0" />
<PackageReference Include="Serilog.Enrichers.Thread" Version="2.0.0" />
<PackageReference Include="Serilog.Filters.Expressions" Version="1.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="4.1.0" />
<PackageReference Include="Serilog.Enrichers.Environment" Version="2.1.3" />
<PackageReference Include="Serilog.Enrichers.Thread" Version="3.1.0" />
<PackageReference Include="Serilog.Filters.Expressions" Version="2.1.0" />
</ItemGroup>

<ItemGroup>
Expand Down
35 changes: 33 additions & 2 deletions sample/Sample/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,44 @@
"Name": "File",
"Args": {
"path": "%TEMP%\\Logs\\serilog-configuration-sample.txt",
"outputTemplate": "{Timestamp:o} [{Level:u3}] ({Application}/{MachineName}/{ThreadId}) {Message}{NewLine}{Exception}"
"outputTemplate": "{Timestamp:o} [{Level:u3}] ({Application}/{MachineName}/{ThreadId}/{ThreadName}) {Message}{NewLine}{Exception}"
}
}
]
}
},
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"WriteTo:ConditionalSink": {
"Name": "Conditional",
"Args": {
"expression": "@Level in ['Error', 'Fatal']",
"configureSink": [
{
"Name": "File",
"Args": {
"path": "%TEMP%\\Logs\\serilog-configuration-sample-errors.txt"
}
}
]
}
},
"Enrich": [
"FromLogContext",
"WithThreadId",
{
"Name": "AtLevel",
"Args": {
"enrichFromLevel": "Error",
"configureEnricher": [ "WithThreadName" ]
}
},
{
"Name": "When",
"Args": {
"expression": "Application = 'Sample'",
"configureEnricher": [ "WithMachineName" ]
}
}
],
"Properties": {
"Application": "Sample"
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

<PropertyGroup>
<Description>Microsoft.Extensions.Configuration (appsettings.json) support for Serilog.</Description>
<VersionPrefix>3.1.1</VersionPrefix>
<VersionPrefix>3.2.0</VersionPrefix>
<LangVersion>latest</LangVersion>
<Authors>Serilog Contributors</Authors>
<TargetFrameworks>netstandard2.0;net451;net461</TargetFrameworks>
Expand Down Expand Up @@ -31,7 +31,7 @@
<ItemGroup>
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0" PrivateAssets="All"/>
<PackageReference Include="Microsoft.Extensions.DependencyModel" Version="3.0.0" />
<PackageReference Include="Serilog" Version="2.6.0" />
<PackageReference Include="Serilog" Version="2.9.0" />
<None Include="..\..\assets\icon.png" Pack="true" PackagePath=""/>
</ItemGroup>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,12 @@ void IConfigurationReader.ApplySinks(LoggerSinkConfiguration loggerSinkConfigura
CallConfigurationMethods(methodCalls, FindSinkConfigurationMethods(_configurationAssemblies), loggerSinkConfiguration);
}

void IConfigurationReader.ApplyEnrichment(LoggerEnrichmentConfiguration loggerEnrichmentConfiguration)
{
var methodCalls = GetMethodCalls(_section);
CallConfigurationMethods(methodCalls, FindEventEnricherConfigurationMethods(_configurationAssemblies), loggerEnrichmentConfiguration);
}

void ApplyEnrichment(LoggerConfiguration loggerConfiguration)
{
var enrichDirective = _section.GetSection("Enrich");
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
using Serilog.Configuration;
using Serilog.Configuration;

namespace Serilog.Settings.Configuration
{
interface IConfigurationReader : ILoggerSettings
{
void ApplySinks(LoggerSinkConfiguration loggerSinkConfiguration);
void ApplyEnrichment(LoggerEnrichmentConfiguration loggerEnrichmentConfiguration);
}
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
using Microsoft.Extensions.Configuration;
using Serilog.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

using Microsoft.Extensions.Configuration;

using Serilog.Configuration;

namespace Serilog.Settings.Configuration
{
class ObjectArgumentValue : IConfigurationArgumentValue
Expand All @@ -31,20 +33,15 @@ public object ConvertTo(Type toType, ResolutionContext resolutionContext)
typeInfo.GetGenericTypeDefinition() is Type genericType && genericType == typeof(Action<>))
{
var configType = typeInfo.GenericTypeArguments[0];
if (configType != typeof(LoggerConfiguration) && configType != typeof(LoggerSinkConfiguration))
throw new ArgumentException($"Configuration for Action<{configType}> is not implemented.");

IConfigurationReader configReader = new ConfigurationReader(_section, _configurationAssemblies, resolutionContext);

if (configType == typeof(LoggerConfiguration))
return configType switch
{
return new Action<LoggerConfiguration>(configReader.Configure);
}

if (configType == typeof(LoggerSinkConfiguration))
{
return new Action<LoggerSinkConfiguration>(loggerSinkConfig => configReader.ApplySinks(loggerSinkConfig));
}
_ when configType == typeof(LoggerConfiguration) => new Action<LoggerConfiguration>(configReader.Configure),
_ when configType == typeof(LoggerSinkConfiguration) => new Action<LoggerSinkConfiguration>(configReader.ApplySinks),
_ when configType == typeof(LoggerEnrichmentConfiguration) => new Action<LoggerEnrichmentConfiguration>(configReader.ApplyEnrichment),
_ => throw new ArgumentException($"Configuration resolution for Action<{configType.Name}> parameter type at the path {_section.Path} is not implemented.")
};
}

if (toType.IsArray)
Expand Down Expand Up @@ -97,7 +94,7 @@ bool TryCreateContainer(out object result)
}
}

private static bool IsContainer(Type type, out Type elementType)
static bool IsContainer(Type type, out Type elementType)
{
elementType = null;
foreach (var iface in type.GetInterfaces())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,14 @@ static LoggerConfiguration With(
ILogEventEnricher enricher)
=> loggerEnrichmentConfiguration.With(enricher);

static LoggerConfiguration AtLevel(
LoggerEnrichmentConfiguration loggerEnrichmentConfiguration,
Action<LoggerEnrichmentConfiguration> configureEnricher,
LogEventLevel enrichFromLevel = LevelAlias.Minimum,
LoggingLevelSwitch levelSwitch = null)
=> levelSwitch != null ? loggerEnrichmentConfiguration.AtLevel(levelSwitch, configureEnricher)
: loggerEnrichmentConfiguration.AtLevel(enrichFromLevel, configureEnricher);

static LoggerConfiguration FromLogContext(LoggerEnrichmentConfiguration loggerEnrichmentConfiguration)
=> loggerEnrichmentConfiguration.FromLogContext();

Expand Down

0 comments on commit 06f8c11

Please sign in to comment.