Skip to content

Fixes #97, #83, #98 #100

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

Merged
merged 13 commits into from
Apr 21, 2018
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
36 changes: 36 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,3 +91,39 @@ For example, to set the minimum log level using the _Windows_ command prompt:
set Serilog:MinimumLevel=Debug
dotnet run
```

### Nested configuration sections
Copy link
Member

Choose a reason for hiding this comment

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

Love the additional docs 👍

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Updated to remove nested config "hint" hack -- but I left the blurb there about nested config support, figured it can't hurt to document it.


Some Serilog packages require a reference to a logger configuration object. The sample program in this project illustrates this with the following entry configuring the _Serilog.Sinks.Async_ package to wrap the _Serilog.Sinks.File_ package. The `configure` parameter references the File sink configuration:

```json
"WriteTo:Async": {
"Name": "Async",
"Args": {
"configure": [
{
"Name": "File",
"Args": {
"path": "%TEMP%\\Logs\\serilog-configuration-sample.txt",
"outputTemplate": "{Timestamp:o} [{Level:u3}] ({Application}/{MachineName}/{ThreadId}) {Message}{NewLine}{Exception}"
}
}
]
}
},
```

### IConfiguration parameter

If a Serilog package requires additional external configuration information (for example, access to a `ConnectionStrings` section, which would be outside of the `Serilog` section), the sink should include an `IConfiguration` parameter in the configuration extension method. This package will automatically populate that parameter. It should not be declared in the argument list in the configuration source.

### 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.

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.

### IConfigurationSection parameters

Certain Serilog packages may require configuration information that can't be easily represented by discrete values or direct binding-friendly representations. An example might be lists of values to remove from a collection of default values. In this case the method can accept an entire `IConfigurationSection` as a call parameter and this package will recognize that and populate the parameter. In this way, Serilog packages can support arbitrarily complex configuration scenarios.
Copy link
Member

Choose a reason for hiding this comment

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

👏

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 think in the long run that one is going to be very useful to sink authors.


Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,18 @@ namespace Serilog
/// </summary>
public static class ConfigurationLoggerConfigurationExtensions
{
const string DefaultSectionName = "Serilog";
/// <summary>
/// Configuration section name required by this package.
/// </summary>
public const string DefaultSectionName = "Serilog";

/// <summary>
/// Reads logger settings from the provided configuration object using the default section name.
/// Reads logger settings from the provided configuration object using the default section name. Generally this
/// is preferable over the other method that takes a configuration section. Only this version will populate
/// IConfiguration parameters on target methods.
/// </summary>
/// <param name="settingConfiguration">Logger setting configuration.</param>
/// <param name="configuration">A configuration object with a Serilog section.</param>
/// <param name="configuration">A configuration object which contains a Serilog section.</param>
/// <param name="dependencyContext">The dependency context from which sink/enricher packages can be located. If not supplied, the platform
/// default will be used.</param>
/// <returns>An object allowing configuration to continue.</returns>
Expand All @@ -42,28 +47,32 @@ public static LoggerConfiguration Configuration(
DependencyContext dependencyContext = null)
{
if (configuration == null) throw new ArgumentNullException(nameof(configuration));
return settingConfiguration.ConfigurationSection(configuration.GetSection(DefaultSectionName), dependencyContext);
return settingConfiguration.Settings(
new ConfigurationReader(
configuration,
dependencyContext ?? (Assembly.GetEntryAssembly() != null ? DependencyContext.Default : null)));
}

/// <summary>
/// Reads logger settings from the provided configuration section.
/// Reads logger settings from the provided configuration section. Generally it is preferable to use the other
/// extension method that takes the full configuration object.
/// </summary>
/// <param name="settingConfiguration">Logger setting configuration.</param>
/// <param name="configuration">The Serilog configuration section</param>
/// <param name="configSection">The Serilog configuration section</param>
/// <param name="dependencyContext">The dependency context from which sink/enricher packages can be located. If not supplied, the platform
/// default will be used.</param>
/// <returns>An object allowing configuration to continue.</returns>
public static LoggerConfiguration ConfigurationSection(
this LoggerSettingsConfiguration settingConfiguration,
IConfigurationSection configuration,
IConfigurationSection configSection,
DependencyContext dependencyContext = null)
{
if (settingConfiguration == null) throw new ArgumentNullException(nameof(settingConfiguration));
if (configuration == null) throw new ArgumentNullException(nameof(configuration));
if (configSection == null) throw new ArgumentNullException(nameof(configSection));

return settingConfiguration.Settings(
new ConfigurationReader(
configuration,
configSection,
dependencyContext ?? (Assembly.GetEntryAssembly() != null ? DependencyContext.Default : null)));
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,12 @@

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

<ItemGroup Condition="'$(TargetFramework)' == 'netstandard2.0'">
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="2.0.1" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="2.0.0" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -20,20 +20,33 @@ class ConfigurationReader : IConfigurationReader
{
const string LevelSwitchNameRegex = @"^\$[A-Za-z]+[A-Za-z0-9]*$";

readonly IConfigurationSection _configuration;
static IConfiguration _configuration;

readonly IConfigurationSection _section;
readonly DependencyContext _dependencyContext;
readonly IReadOnlyCollection<Assembly> _configurationAssemblies;

public ConfigurationReader(IConfigurationSection configuration, DependencyContext dependencyContext)
public ConfigurationReader(IConfiguration configuration, DependencyContext dependencyContext)
{
_configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
_section = configuration.GetSection(ConfigurationLoggerConfigurationExtensions.DefaultSectionName);
_dependencyContext = dependencyContext;
_configurationAssemblies = LoadConfigurationAssemblies();
}

ConfigurationReader(IConfigurationSection configuration, IReadOnlyCollection<Assembly> configurationAssemblies, DependencyContext dependencyContext)
// Generally the initial call should use IConfiguration rather than IConfigurationSection, otherwise
// IConfiguration parameters in the target methods will not be populated.
ConfigurationReader(IConfigurationSection configSection, DependencyContext dependencyContext)
{
_configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
_section = configSection ?? throw new ArgumentNullException(nameof(configSection));
_dependencyContext = dependencyContext;
_configurationAssemblies = LoadConfigurationAssemblies();
}

// Used internally for processing nested configuration sections -- see GetMethodCalls below.
internal ConfigurationReader(IConfigurationSection configSection, IReadOnlyCollection<Assembly> configurationAssemblies, DependencyContext dependencyContext)
{
_section = configSection ?? throw new ArgumentNullException(nameof(configSection));
_dependencyContext = dependencyContext;
_configurationAssemblies = configurationAssemblies ?? throw new ArgumentNullException(nameof(configurationAssemblies));
}
Expand All @@ -50,40 +63,35 @@ public void Configure(LoggerConfiguration loggerConfiguration)

IReadOnlyDictionary<string, LoggingLevelSwitch> ProcessLevelSwitchDeclarations()
{
var levelSwitchesDirective = _configuration.GetSection("LevelSwitches");
var levelSwitchesDirective = _section.GetSection("LevelSwitches");
var namedSwitches = new Dictionary<string, LoggingLevelSwitch>();
if (levelSwitchesDirective != null)
foreach (var levelSwitchDeclaration in levelSwitchesDirective.GetChildren())
{
foreach (var levelSwitchDeclaration in levelSwitchesDirective.GetChildren())
var switchName = levelSwitchDeclaration.Key;
var switchInitialLevel = levelSwitchDeclaration.Value;
// switchName must be something like $switch to avoid ambiguities
if (!IsValidSwitchName(switchName))
{
var switchName = levelSwitchDeclaration.Key;
var switchInitialLevel = levelSwitchDeclaration.Value;
// switchName must be something like $switch to avoid ambiguities
if (!IsValidSwitchName(switchName))
{
throw new FormatException($"\"{switchName}\" is not a valid name for a Level Switch declaration. Level switch must be declared with a '$' sign, like \"LevelSwitches\" : {{\"$switchName\" : \"InitialLevel\"}}");
}
LoggingLevelSwitch newSwitch;
if (string.IsNullOrEmpty(switchInitialLevel))
{
newSwitch = new LoggingLevelSwitch();
}
else
{
var initialLevel = ParseLogEventLevel(switchInitialLevel);
newSwitch = new LoggingLevelSwitch(initialLevel);
}
namedSwitches.Add(switchName, newSwitch);
throw new FormatException($"\"{switchName}\" is not a valid name for a Level Switch declaration. Level switch must be declared with a '$' sign, like \"LevelSwitches\" : {{\"$switchName\" : \"InitialLevel\"}}");
}
LoggingLevelSwitch newSwitch;
if (string.IsNullOrEmpty(switchInitialLevel))
{
newSwitch = new LoggingLevelSwitch();
}
else
{
var initialLevel = ParseLogEventLevel(switchInitialLevel);
newSwitch = new LoggingLevelSwitch(initialLevel);
}
namedSwitches.Add(switchName, newSwitch);
}

return namedSwitches;
}

void ApplyMinimumLevel(LoggerConfiguration loggerConfiguration,
IReadOnlyDictionary<string, LoggingLevelSwitch> declaredLevelSwitches)
void ApplyMinimumLevel(LoggerConfiguration loggerConfiguration, IReadOnlyDictionary<string, LoggingLevelSwitch> declaredLevelSwitches)
{
var minimumLevelDirective = _configuration.GetSection("MinimumLevel");
var minimumLevelDirective = _section.GetSection("MinimumLevel");

var defaultMinLevelDirective = minimumLevelDirective.Value != null ? minimumLevelDirective : minimumLevelDirective.GetSection("Default");
if (defaultMinLevelDirective.Value != null)
Expand All @@ -92,7 +100,7 @@ void ApplyMinimumLevel(LoggerConfiguration loggerConfiguration,
}

var minLevelControlledByDirective = minimumLevelDirective.GetSection("ControlledBy");
if (minLevelControlledByDirective?.Value != null)
if (minLevelControlledByDirective.Value != null)
{
var globalMinimumLevelSwitch = declaredLevelSwitches.LookUpSwitchByName(minLevelControlledByDirective.Value);
// not calling ApplyMinimumLevel local function because here we have a reference to a LogLevelSwitch already
Expand Down Expand Up @@ -134,60 +142,53 @@ void ApplyMinimumLevel(IConfigurationSection directive, Action<LoggerMinimumLeve
}
}



void ApplyFilters(LoggerConfiguration loggerConfiguration,
IReadOnlyDictionary<string, LoggingLevelSwitch> declaredLevelSwitches)
void ApplyFilters(LoggerConfiguration loggerConfiguration, IReadOnlyDictionary<string, LoggingLevelSwitch> declaredLevelSwitches)
{
var filterDirective = _configuration.GetSection("Filter");
if (filterDirective != null)
var filterDirective = _section.GetSection("Filter");
if (filterDirective.GetChildren().Any())
{
var methodCalls = GetMethodCalls(filterDirective);
CallConfigurationMethods(methodCalls, FindFilterConfigurationMethods(_configurationAssemblies), loggerConfiguration.Filter, declaredLevelSwitches);
}
}

void ApplySinks(LoggerConfiguration loggerConfiguration,
IReadOnlyDictionary<string, LoggingLevelSwitch> declaredLevelSwitches)
void ApplySinks(LoggerConfiguration loggerConfiguration, IReadOnlyDictionary<string, LoggingLevelSwitch> declaredLevelSwitches)
{
var writeToDirective = _configuration.GetSection("WriteTo");
if (writeToDirective != null)
var writeToDirective = _section.GetSection("WriteTo");
if (writeToDirective.GetChildren().Any())
{
var methodCalls = GetMethodCalls(writeToDirective);
CallConfigurationMethods(methodCalls, FindSinkConfigurationMethods(_configurationAssemblies), loggerConfiguration.WriteTo, declaredLevelSwitches);
}
}

void ApplyAuditSinks(LoggerConfiguration loggerConfiguration,
IReadOnlyDictionary<string, LoggingLevelSwitch> declaredLevelSwitches)
void ApplyAuditSinks(LoggerConfiguration loggerConfiguration, IReadOnlyDictionary<string, LoggingLevelSwitch> declaredLevelSwitches)
{
var auditToDirective = _configuration.GetSection("AuditTo");
if (auditToDirective != null)
var auditToDirective = _section.GetSection("AuditTo");
if (auditToDirective.GetChildren().Any())
{
var methodCalls = GetMethodCalls(auditToDirective);
CallConfigurationMethods(methodCalls, FindAuditSinkConfigurationMethods(_configurationAssemblies), loggerConfiguration.AuditTo, declaredLevelSwitches);
}
}

void IConfigurationReader.ApplySinks(LoggerSinkConfiguration loggerSinkConfiguration,
IReadOnlyDictionary<string, LoggingLevelSwitch> declaredLevelSwitches)
void IConfigurationReader.ApplySinks(LoggerSinkConfiguration loggerSinkConfiguration, IReadOnlyDictionary<string, LoggingLevelSwitch> declaredLevelSwitches)
{
var methodCalls = GetMethodCalls(_configuration);
var methodCalls = GetMethodCalls(_section);
CallConfigurationMethods(methodCalls, FindSinkConfigurationMethods(_configurationAssemblies), loggerSinkConfiguration, declaredLevelSwitches);
}

void ApplyEnrichment(LoggerConfiguration loggerConfiguration,
IReadOnlyDictionary<string, LoggingLevelSwitch> declaredLevelSwitches)
void ApplyEnrichment(LoggerConfiguration loggerConfiguration, IReadOnlyDictionary<string, LoggingLevelSwitch> declaredLevelSwitches)
{
var enrichDirective = _configuration.GetSection("Enrich");
if (enrichDirective != null)
var enrichDirective = _section.GetSection("Enrich");
if (enrichDirective.GetChildren().Any())
{
var methodCalls = GetMethodCalls(enrichDirective);
CallConfigurationMethods(methodCalls, FindEventEnricherConfigurationMethods(_configurationAssemblies), loggerConfiguration.Enrich, declaredLevelSwitches);
}

var propertiesDirective = _configuration.GetSection("Properties");
if (propertiesDirective != null)
var propertiesDirective = _section.GetSection("Properties");
if (propertiesDirective.GetChildren().Any())
{
foreach (var enrichProperyDirective in propertiesDirective.GetChildren())
{
Expand Down Expand Up @@ -226,7 +227,7 @@ IConfigurationArgumentValue GetArgumentValue(IConfigurationSection argumentSecti
}
else
{
argumentValue = new ConfigurationSectionArgumentValue(new ConfigurationReader(argumentSection, _configurationAssemblies, _dependencyContext));
argumentValue = new ObjectArgumentValue(argumentSection, _configurationAssemblies, _dependencyContext);
}

return argumentValue;
Expand All @@ -246,8 +247,8 @@ IReadOnlyCollection<Assembly> LoadConfigurationAssemblies()
{
var assemblies = new Dictionary<string, Assembly>();

var usingSection = _configuration.GetSection("Using");
if (usingSection != null)
var usingSection = _section.GetSection("Using");
if (usingSection.GetChildren().Any())
{
foreach (var simpleName in usingSection.GetChildren().Select(c => c.Value))
{
Expand Down Expand Up @@ -307,6 +308,9 @@ static void CallConfigurationMethods(ILookup<string, Dictionary<string, IConfigu
let directive = method.Value.FirstOrDefault(s => s.Key == p.Name)
select directive.Key == null ? p.DefaultValue : directive.Value.ConvertTo(p.ParameterType, declaredLevelSwitches)).ToList();

var parm = methodInfo.GetParameters().FirstOrDefault(i => i.ParameterType == typeof(IConfiguration));
if(parm != null) call[parm.Position - 1] = _configuration;

call.Insert(0, receiver);

methodInfo.Invoke(null, call.ToArray());
Expand Down Expand Up @@ -399,5 +403,6 @@ internal static LogEventLevel ParseLogEventLevel(string value)
throw new InvalidOperationException($"The value {value} is not a valid Serilog level.");
return parsedLevel;
}

}
}
Loading