Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for custom types in arrays and custom collections #201

Closed
wants to merge 8 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions Build.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ echo "build: Build started"

Push-Location $PSScriptRoot

if(Test-Path .\artifacts) {
if (Test-Path .\artifacts) {
echo "build: Cleaning .\artifacts"
Remove-Item .\artifacts -Force -Recurse
}
Expand All @@ -21,7 +21,7 @@ foreach ($src in ls src/*) {
echo "build: Packaging project in $src"

& dotnet pack -c Release -o ..\..\artifacts --version-suffix=$suffix --include-source
if($LASTEXITCODE -ne 0) { exit 1 }
if ($LASTEXITCODE -ne 0) { exit 1 }

Pop-Location
}
Expand All @@ -32,7 +32,7 @@ foreach ($test in ls test/*.PerformanceTests) {
echo "build: Building performance test project in $test"

& dotnet build -c Release
if($LASTEXITCODE -ne 0) { exit 2 }
if ($LASTEXITCODE -ne 0) { exit 2 }

Pop-Location
}
Expand All @@ -43,7 +43,7 @@ foreach ($test in ls test/*.Tests) {
echo "build: Testing project in $test"

& dotnet test -c Release
if($LASTEXITCODE -ne 0) { exit 3 }
if ($LASTEXITCODE -ne 0) { exit 3 }

Pop-Location
}
Expand Down
11 changes: 6 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Serilog.Settings.Configuration [![Build status](https://ci.appveyor.com/api/projects/status/r2bgfimd9ocr61px/branch/master?svg=true)](https://ci.appveyor.com/project/serilog/serilog-settings-configuration/branch/master) [![NuGet Version](http://img.shields.io/nuget/v/Serilog.Settings.Configuration.svg?style=flat)](https://www.nuget.org/packages/Serilog.Settings.Configuration/)

A Serilog settings provider that reads from _Microsoft.Extensions.Configuration_, .NET Core's `appsettings.json` file.
A Serilog settings provider that reads from _Microsoft.Extensions.Configuration_ sources, including .NET Core's `appsettings.json` file.

Configuration is read from the `Serilog` section.

Expand All @@ -21,13 +21,13 @@ Configuration is read from the `Serilog` section.
{ "Name": "ToMaximumCollectionCount", "Args": { "maximumCollectionCount": 10 } }
],
"Properties": {
"Application": "Sample"
"Application": "Sample"
}
}
}
```

This example relies on the _Serilog.Sinks.Console_, _Serilog.Sinks.File_, _Serilog.Enrichers.Environment_, _Serilog.Settings.Configuration_ and _Serilog.Enrichers.Thread_ packages also being installed.
This example relies on the _Microsoft.Extensions.Configuration.Json_, _Serilog.Sinks.Console_, _Serilog.Sinks.File_, _Serilog.Enrichers.Environment_, _Serilog.Settings.Configuration_ and _Serilog.Enrichers.Thread_ packages also being installed.

After installing this package, use `ReadFrom.Configuration()` and pass an `IConfiguration` object.

Expand Down Expand Up @@ -111,7 +111,8 @@ Some Serilog packages require a reference to a logger configuration object. The
"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}) {Message}{NewLine}{Exception}"
}
}
]
Expand All @@ -125,7 +126,7 @@ If a Serilog package requires additional external configuration information (for

### Complex parameter value binding

When the configuration specifies a discrete value for a parameter (such as a string literal), the package will attempt to convert that value to the target method's declared CLR type of the parameter. Additional explicit handling is provided for parsing strings to `Uri` and `TimeSpan` objects and `enum` elements.
When the configuration specifies a discrete value for a parameter (such as a string literal), the package will attempt to convert that value to the target method's declared CLR type of the parameter. Additional explicit handling is provided for parsing strings to `Uri`, `TimeSpan`, `enum` and arrays.

If the parameter value is not a discrete value, the package will use the configuration binding system provided by _Microsoft.Extensions.Options.ConfigurationExtensions_ to attempt to populate the parameter. Almost anything that can be bound by `IConfiguration.Get<T>` should work with this package. An example of this is the optional `List<Column>` parameter used to configure the .NET Standard version of the _Serilog.Sinks.MSSqlServer_ package.

Expand Down
2 changes: 1 addition & 1 deletion appveyor.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
version: '{build}'
skip_tags: true
image: Visual Studio 2017
image: Visual Studio 2019
configuration: Release
build_script:
- ps: ./Build.ps1
Expand Down
Binary file added assets/icon.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<Description>Microsoft.Extensions.Configuration (appsettings.json) support for Serilog.</Description>
<VersionPrefix>3.1.0</VersionPrefix>
<VersionPrefix>3.1.1</VersionPrefix>
<LangVersion>latest</LangVersion>
<Authors>Serilog Contributors</Authors>
<TargetFrameworks>netstandard2.0;net451;net461</TargetFrameworks>
<TargetFrameworks>netstandard2.0;net451;net452;net461</TargetFrameworks>
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What's the reason for the additional target framework here?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added this target because I saw references to it in the conditions.

<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<AssemblyName>Serilog.Settings.Configuration</AssemblyName>
Expand All @@ -13,28 +14,29 @@
<PublicSign Condition=" '$(OS)' != 'Windows_NT' ">true</PublicSign>
<PackageId>Serilog.Settings.Configuration</PackageId>
<PackageTags>serilog;json</PackageTags>
<PackageIconUrl>https://serilog.net/images/serilog-configuration-nuget.png</PackageIconUrl>
<PackageIcon>icon.png</PackageIcon>
<PackageProjectUrl>https://github.com/serilog/serilog-settings-configuration</PackageProjectUrl>
<PackageLicenseExpression>Apache-2.0</PackageLicenseExpression>
<RepositoryUrl>https://github.com/serilog/serilog-settings-configuration</RepositoryUrl>
<RepositoryType>git</RepositoryType>
<RootNamespace>Serilog</RootNamespace>
</PropertyGroup>

<PropertyGroup Condition="('$(TargetFramework)' == 'net451') Or ('$(TargetFramework)' == 'net461')">
<PropertyGroup Condition="'$(TargetFramework)' == 'net451' or '$(TargetFramework)' == 'net452' or '$(TargetFramework)' == 'net461'">
<DefineConstants>$(DefineConstants);PRIVATE_BIN</DefineConstants>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyModel" Version="2.0.4" />
<PackageReference Include="Serilog" Version="2.6.0" />
<None Include="..\..\assets\icon.png" Pack="true" PackagePath=""/>
</ItemGroup>

<ItemGroup Condition="'$(TargetFramework)' == 'net451'">
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="1.1.2" />
<ItemGroup Condition="'$(TargetFramework)' == 'net451' or '$(TargetFramework)' == 'net452'">
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="1.1.1" />
</ItemGroup>

<ItemGroup Condition="('$(TargetFramework)' == 'netstandard2.0') Or ('$(TargetFramework)' == 'net461')">
<ItemGroup Condition="'$(TargetFramework)' == 'netstandard2.0' or '$(TargetFramework)' == 'net461'">
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="2.0.0" />
</ItemGroup>
</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,12 @@ public static AssemblyFinder Auto()

public static AssemblyFinder ForSource(ConfigurationAssemblySource configurationAssemblySource)
{
switch (configurationAssemblySource)
return configurationAssemblySource switch
{
case ConfigurationAssemblySource.UseLoadedAssemblies:
return Auto();
case ConfigurationAssemblySource.AlwaysScanDllFiles:
return new DllScanningAssemblyFinder();
default:
throw new ArgumentOutOfRangeException(nameof(configurationAssemblySource), configurationAssemblySource, null);
}
ConfigurationAssemblySource.UseLoadedAssemblies => Auto(),
ConfigurationAssemblySource.AlwaysScanDllFiles => new DllScanningAssemblyFinder(),
_ => throw new ArgumentOutOfRangeException(nameof(configurationAssemblySource), configurationAssemblySource, null),
};
}

public static AssemblyFinder ForDependencyContext(DependencyContext dependencyContext)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ where IsCaseInsensitiveMatch(assemblyFileName, nameToFind)

return query.ToList().AsReadOnly();

AssemblyName TryGetAssemblyNameFrom(string path)
static AssemblyName TryGetAssemblyNameFrom(string path)
{
try
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -220,39 +220,14 @@ internal ILookup<string, Dictionary<string, IConfigurationArgumentValue>> GetMet
select new
{
Name = argument.Key,
Value = GetArgumentValue(argument)
Value = GetArgumentValue(argument, _configurationAssemblies)
}).ToDictionary(p => p.Name, p => p.Value)
select new { Name = name, Args = callArgs }))
.ToLookup(p => p.Name, p => p.Args);

return result;

IConfigurationArgumentValue GetArgumentValue(IConfigurationSection argumentSection)
{
IConfigurationArgumentValue argumentValue;

// Reject configurations where an element has both scalar and complex
// values as a result of reading multiple configuration sources.
if (argumentSection.Value != null && argumentSection.GetChildren().Any())
throw new InvalidOperationException(
$"The value for the argument '{argumentSection.Path}' is assigned different value " +
"types in more than one configuration source. Ensure all configurations consistently " +
"use either a scalar (int, string, boolean) or a complex (array, section, list, " +
"POCO, etc.) type for this argument value.");

if (argumentSection.Value != null)
{
argumentValue = new StringArgumentValue(argumentSection.Value);
}
else
{
argumentValue = new ObjectArgumentValue(argumentSection, _configurationAssemblies);
}

return argumentValue;
}

string GetSectionName(IConfigurationSection s)
static string GetSectionName(IConfigurationSection s)
{
var name = s.GetSection("Name");
if (name.Value == null)
Expand All @@ -262,6 +237,31 @@ string GetSectionName(IConfigurationSection s)
}
}

internal static IConfigurationArgumentValue GetArgumentValue(IConfigurationSection argumentSection, IReadOnlyCollection<Assembly> configurationAssemblies)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it began to be used in another place

{
IConfigurationArgumentValue argumentValue;

// Reject configurations where an element has both scalar and complex
// values as a result of reading multiple configuration sources.
if (argumentSection.Value != null && argumentSection.GetChildren().Any())
throw new InvalidOperationException(
$"The value for the argument '{argumentSection.Path}' is assigned different value " +
"types in more than one configuration source. Ensure all configurations consistently " +
"use either a scalar (int, string, boolean) or a complex (array, section, list, " +
"POCO, etc.) type for this argument value.");

if (argumentSection.Value != null)
{
argumentValue = new StringArgumentValue(argumentSection.Value);
}
else
{
argumentValue = new ObjectArgumentValue(argumentSection, configurationAssemblies);
}

return argumentValue;
}

static IReadOnlyCollection<Assembly> LoadConfigurationAssemblies(IConfigurationSection section, AssemblyFinder assemblyFinder)
{
var assemblies = new Dictionary<string, Assembly>();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
using Microsoft.Extensions.Configuration;
using Serilog.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

using Serilog.Configuration;

namespace Serilog.Settings.Configuration
{
class ObjectArgumentValue : IConfigurationArgumentValue
Expand Down Expand Up @@ -47,8 +47,72 @@ public object ConvertTo(Type toType, ResolutionContext resolutionContext)
}
}

// MS Config binding
if (toType.IsArray)
return CreateArray();

if (IsContainer(toType, out var elementType) && TryCreateContainer(out var result))
return result;

// MS Config binding can work with a limited set of primitive types and collections
return _section.Get(toType);

object CreateArray()
{
var elementType = toType.GetElementType();
var configurationElements = _section.GetChildren().ToArray();
var result = Array.CreateInstance(elementType, configurationElements.Length);
for (int i = 0; i < configurationElements.Length; ++i)
{
var argumentValue = ConfigurationReader.GetArgumentValue(configurationElements[i], _configurationAssemblies);
var value = argumentValue.ConvertTo(elementType, resolutionContext);
result.SetValue(value, i);
}

return result;
}

bool TryCreateContainer(out object result)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If false fallbacks to ms config binding implementation.

{
result = null;

if (toType.GetConstructor(Type.EmptyTypes) == null)
return false;

// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/object-and-collection-initializers#collection-initializers
var addMethod = toType.GetMethods().FirstOrDefault(m => !m.IsStatic && m.Name == "Add" && m.GetParameters()?.Length == 1 && m.GetParameters()[0].ParameterType == elementType);
if (addMethod == null)
return false;

var configurationElements = _section.GetChildren().ToArray();
result = Activator.CreateInstance(toType);

for (int i = 0; i < configurationElements.Length; ++i)
{
var argumentValue = ConfigurationReader.GetArgumentValue(configurationElements[i], _configurationAssemblies);
var value = argumentValue.ConvertTo(elementType, resolutionContext);
addMethod.Invoke(result, new object[] { value });
}

return true;
}
}

private static bool IsContainer(Type type, out Type elementType)
{
elementType = null;
foreach (var iface in type.GetInterfaces())
{
if (iface.IsGenericType)
{
if (iface.GetGenericTypeDefinition() == typeof(IEnumerable<>))
{
elementType = iface.GetGenericArguments()[0];
return true;
}
}
}

return false;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -584,6 +584,46 @@ public void SinkWithStringArrayArgument()
Assert.Equal(1, DummyRollingFileSink.Emitted.Count);
}

[Fact]
public void DestructureWithCollectionsOfTypeArgument()
{
var json = @"{
""Serilog"": {
""Using"": [ ""TestDummies"" ],
""Destructure"": [{
""Name"": ""DummyArrayOfType"",
""Args"": {
""list"": [
""System.Byte"",
""System.Int16""
],
""array"" : [
""System.Int32"",
""System.String""
],
""type"" : ""System.TimeSpan"",
""custom"" : [
""System.Int64""
],
""customString"" : [
""System.UInt32""
]
}
}]
}
}";

DummyPolicy.Current = null;

ConfigFromJson(json);

Assert.Equal(typeof(TimeSpan), DummyPolicy.Current.Type);
Assert.Equal(new[] { typeof(int), typeof(string) }, DummyPolicy.Current.Array);
Assert.Equal(new[] { typeof(byte), typeof(short) }, DummyPolicy.Current.List);
Assert.Equal(typeof(long), DummyPolicy.Current.Custom.First);
Assert.Equal("System.UInt32", DummyPolicy.Current.CustomStrings.First);
}

[Fact]
public void SinkWithIntArrayArgument()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ public void ShouldProbePrivateBinPath()
AppDomain.Unload(ad);
}

void DoTestInner()
static void DoTestInner()
{
var assemblyNames = new DllScanningAssemblyFinder().FindAssembliesContainingName("customSink");
Assert.Equal(2, assemblyNames.Count);
Expand Down
Loading