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

Support for static member as the value of setting using :: #73 #77

Merged
merged 10 commits into from
Dec 15, 2017
Merged
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
2 changes: 2 additions & 0 deletions sample/Sample/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@ public static void Main(string[] args)
do
{
logger.ForContext<Program>().Information("Hello, world!");
logger.ForContext<Program>().Error("Hello, world!");
logger.ForContext(Constants.SourceContextPropertyName, "Microsoft").Warning("Hello, world!");
logger.ForContext(Constants.SourceContextPropertyName, "Microsoft").Error("Hello, world!");
logger.ForContext(Constants.SourceContextPropertyName, "MyApp.Something.Tricky").Verbose("Hello, world!");

Console.WriteLine();
Expand Down
2 changes: 1 addition & 1 deletion sample/Sample/Sample.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="1.1.1" />
<PackageReference Include="Serilog.Sinks.Async" Version="1.0.1" />
<PackageReference Include="Serilog.Sinks.Literate" Version="2.0.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" />
Expand Down
7 changes: 4 additions & 3 deletions sample/Sample/appsettings.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"Serilog": {
"Using": ["Serilog.Sinks.Literate"],
"Using": ["Serilog.Sinks.Console"],
"MinimumLevel": {
"Default": "Debug",
"Override": {
Expand All @@ -14,9 +14,10 @@
"configureLogger": {
"WriteTo": [
{
"Name": "LiterateConsole",
"Name": "Console",
"Args": {
"outputTemplate": "[{Timestamp:HH:mm:ss} {SourceContext} [{Level}] {Message}{NewLine}{Exception}"
"outputTemplate": "[{Timestamp:HH:mm:ss} {SourceContext} [{Level}] {Message}{NewLine}{Exception}",
"theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Code, Serilog.Sinks.Console"
}
}
]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

using System.Text.RegularExpressions;
using Microsoft.Extensions.Primitives;

using Serilog.Core;
Expand All @@ -16,6 +16,8 @@ class StringArgumentValue : IConfigurationArgumentValue
readonly Func<string> _valueProducer;
readonly Func<IChangeToken> _changeTokenProducer;

private static readonly Regex StaticMemberAccessorRegex = new Regex("^(?<shortTypeName>[^:]+)::(?<memberName>[A-Za-z][A-Za-z0-9]*)(?<typeNameExtraQualifiers>[^:]*)$");

public StringArgumentValue(Func<string> valueProducer, Func<IChangeToken> changeTokenProducer = null)
{
_valueProducer = valueProducer ?? throw new ArgumentNullException(nameof(valueProducer));
Expand Down Expand Up @@ -56,6 +58,39 @@ public object ConvertTo(Type toType)

if ((toTypeInfo.IsInterface || toTypeInfo.IsAbstract) && !string.IsNullOrWhiteSpace(argumentValue))
{
//check if value looks like a static property or field directive
// like "Namespace.TypeName::StaticProperty, AssemblyName"
if (TryParseStaticMemberAccessor(argumentValue, out var accessorTypeName, out var memberName))
{
var accessorType = Type.GetType(accessorTypeName, throwOnError: true);
// is there a public static property with that name ?
var publicStaticPropertyInfo = accessorType.GetTypeInfo().DeclaredProperties
.Where(x => x.Name == memberName)
.Where(x => x.GetMethod != null)
.Where(x => x.GetMethod.IsPublic)
.FirstOrDefault(x => x.GetMethod.IsStatic);

if (publicStaticPropertyInfo != null)
{
return publicStaticPropertyInfo.GetValue(null); // static property, no instance to pass
}

// no property ? look for a public static field
var publicStaticFieldInfo = accessorType.GetTypeInfo().DeclaredFields
.Where(x => x.Name == memberName)
.Where(x => x.IsPublic)
.FirstOrDefault(x => x.IsStatic);

if (publicStaticFieldInfo != null)
{
return publicStaticFieldInfo.GetValue(null); // static field, no instance to pass
}

throw new InvalidOperationException($"Could not find a public static property or field with name `{memberName}` on type `{accessorTypeName}`");
}

// maybe it's the assembly-qualified type name of a concrete implementation
// with a default constructor
var type = Type.GetType(argumentValue.Trim());
if (type != null)
{
Expand Down Expand Up @@ -100,5 +135,29 @@ public object ConvertTo(Type toType)

return Convert.ChangeType(argumentValue, toType);
}

internal static bool TryParseStaticMemberAccessor(string input, out string accessorTypeName, out string memberName)
{
if (input == null)
{
accessorTypeName = null;
memberName = null;
return false;
}
if (StaticMemberAccessorRegex.IsMatch(input))
{
var match = StaticMemberAccessorRegex.Match(input);
var shortAccessorTypeName = match.Groups["shortTypeName"].Value;
var rawMemberName = match.Groups["memberName"].Value;
var extraQualifiers = match.Groups["typeNameExtraQualifiers"].Value;

memberName = rawMemberName.Trim();
accessorTypeName = shortAccessorTypeName.Trim() + extraQualifiers.TrimEnd();
return true;
}
accessorTypeName = null;
memberName = null;
return false;
}
}
}
109 changes: 103 additions & 6 deletions test/Serilog.Settings.Configuration.Tests/StringArgumentValueTests.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
using Serilog.Formatting;
using System;
using Serilog.Formatting;
using Serilog.Formatting.Json;

using Serilog.Settings.Configuration.Tests.Support;

using Xunit;

namespace Serilog.Settings.Configuration.Tests
Expand All @@ -20,11 +23,105 @@ public void StringValuesConvertToDefaultInstancesIfTargetIsInterface()
[Fact]
public void StringValuesConvertToDefaultInstancesIfTargetIsAbstractClass()
{
var stringArgumentValue = new StringArgumentValue(() => "Serilog.Settings.Configuration.Tests.Support.ConcreteClass, Serilog.Settings.Configuration.Tests");
var stringArgumentValue = new StringArgumentValue(() => "Serilog.Settings.Configuration.Tests.Support.ConcreteClass, Serilog.Settings.Configuration.Tests");

var result = stringArgumentValue.ConvertTo(typeof(AbstractClass));

Assert.IsType<ConcreteClass>(result);
}

[Theory]
[InlineData("My.NameSpace.Class+InnerClass::Member",
"My.NameSpace.Class+InnerClass", "Member")]
[InlineData(" TrimMe.NameSpace.Class::NeedsTrimming ",
"TrimMe.NameSpace.Class", "NeedsTrimming")]
[InlineData("My.NameSpace.Class::Member",
"My.NameSpace.Class", "Member")]
[InlineData("My.NameSpace.Class::Member, MyAssembly",
"My.NameSpace.Class, MyAssembly", "Member")]
[InlineData("My.NameSpace.Class::Member, MyAssembly, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
"My.NameSpace.Class, MyAssembly, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "Member")]
[InlineData("Just a random string with :: in it",
null, null)]
[InlineData("Its::a::trapWithColonsAppearingTwice",
null, null)]
[InlineData("ThereIsNoMemberHere::",
null, null)]
[InlineData(null,
null, null)]
[InlineData(" ",
null, null)]
// a full-qualified type name should not be considered a static member accessor
[InlineData("My.NameSpace.Class, MyAssembly, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
null, null)]
public void TryParseStaticMemberAccessorReturnsExpectedResults(string input, string expectedAccessorType, string expectedPropertyName)
{
var actual = StringArgumentValue.TryParseStaticMemberAccessor(input,
out var actualAccessorType,
out var actualMemberName);

if (expectedAccessorType == null)
{
Assert.False(actual, $"Should not parse {input}");
}
else
{
Assert.True(actual, $"should successfully parse {input}");
Assert.Equal(expectedAccessorType, actualAccessorType);
Assert.Equal(expectedPropertyName, actualMemberName);
}
}

[Theory]
[InlineData("Serilog.Settings.Configuration.Tests.Support.ClassWithStaticAccessors::InterfaceProperty, Serilog.Settings.Configuration.Tests", typeof(IAmAnInterface))]
[InlineData("Serilog.Settings.Configuration.Tests.Support.ClassWithStaticAccessors::AbstractProperty, Serilog.Settings.Configuration.Tests", typeof(AnAbstractClass))]
[InlineData("Serilog.Settings.Configuration.Tests.Support.ClassWithStaticAccessors::InterfaceField, Serilog.Settings.Configuration.Tests", typeof(IAmAnInterface))]
[InlineData("Serilog.Settings.Configuration.Tests.Support.ClassWithStaticAccessors::AbstractField, Serilog.Settings.Configuration.Tests", typeof(AnAbstractClass))]
private void StaticMembersAccessorsCanBeUsedForReferenceTypes(string input, Type targetType)
{
var stringArgumentValue = new StringArgumentValue(() => $"{input}");

var actual = stringArgumentValue.ConvertTo(targetType);

Assert.IsAssignableFrom(targetType, actual);
Assert.Equal(ConcreteImpl.Instance, actual);
}

var result = stringArgumentValue.ConvertTo(typeof(AbstractClass));
[Theory]
// unknown type
[InlineData("Namespace.ThisIsNotAKnownType::InterfaceProperty, Serilog.Settings.Configuration.Tests", typeof(IAmAnInterface))]
// good type name, but wrong namespace
[InlineData("Random.Namespace.ClassWithStaticAccessors::InterfaceProperty, Serilog.Settings.Configuration.Tests", typeof(IAmAnInterface))]
// good full type name, but missing or wrong assembly
[InlineData("Serilog.Settings.Configuration.Tests.Support.ClassWithStaticAccessors::InterfaceProperty", typeof(IAmAnInterface))]
public void StaticAccessorOnUnknownTypeThrowsTypeLoadException(string input, Type targetType)
{
var stringArgumentValue = new StringArgumentValue(() => $"{input}");
Assert.Throws<TypeLoadException>(() =>
stringArgumentValue.ConvertTo(targetType)
);
}

[Theory]
// unknown member
[InlineData("Serilog.Settings.Configuration.Tests.Support.ClassWithStaticAccessors::UnknownMember, Serilog.Settings.Configuration.Tests", typeof(IAmAnInterface))]
// static property exists but it's private
[InlineData("Serilog.Settings.Configuration.Tests.Support.ClassWithStaticAccessors::PrivateInterfaceProperty, Serilog.Settings.Configuration.Tests", typeof(IAmAnInterface))]
// static field exists but it's private
[InlineData("Serilog.Settings.Configuration.Tests.Support.ClassWithStaticAccessors::PrivateInterfaceField, Serilog.Settings.Configuration.Tests", typeof(IAmAnInterface))]
// public property exists but it's not static
[InlineData("Serilog.Settings.Configuration.Tests.Support.ClassWithStaticAccessors::InstanceInterfaceProperty, Serilog.Settings.Configuration.Tests", typeof(IAmAnInterface))]
// public field exists but it's not static
[InlineData("Serilog.Settings.Configuration.Tests.Support.ClassWithStaticAccessors::InstanceInterfaceField, Serilog.Settings.Configuration.Tests", typeof(IAmAnInterface))]
public void StaticAccessorWithInvalidMemberThrowsInvalidOperationException(string input, Type targetType)
{
var stringArgumentValue = new StringArgumentValue(() => $"{input}");
var exception = Assert.Throws<InvalidOperationException>(() =>
stringArgumentValue.ConvertTo(targetType)
);

Assert.IsType<ConcreteClass>(result);
Assert.Contains("Could not find a public static property or field ", exception.Message);
Assert.Contains("on type `Serilog.Settings.Configuration.Tests.Support.ClassWithStaticAccessors, Serilog.Settings.Configuration.Tests`", exception.Message);
}
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
namespace Serilog.Settings.Configuration.Tests.Support
{
public interface IAmAnInterface
{
}

public abstract class AnAbstractClass
{
}

internal class ConcreteImpl : AnAbstractClass, IAmAnInterface
{
private ConcreteImpl()
{
}

public static ConcreteImpl Instance { get; } = new ConcreteImpl();
}

public class ClassWithStaticAccessors
{
public static IAmAnInterface InterfaceProperty => ConcreteImpl.Instance;
public static AnAbstractClass AbstractProperty => ConcreteImpl.Instance;

public static IAmAnInterface InterfaceField = ConcreteImpl.Instance;
public static AnAbstractClass AbstractField = ConcreteImpl.Instance;

// ReSharper disable once UnusedMember.Local
private static IAmAnInterface PrivateInterfaceProperty => ConcreteImpl.Instance;

#pragma warning disable 169
private static IAmAnInterface PrivateInterfaceField = ConcreteImpl.Instance;
#pragma warning restore 169
public IAmAnInterface InstanceInterfaceProperty => ConcreteImpl.Instance;
public IAmAnInterface InstanceInterfaceField = ConcreteImpl.Instance;
}
}