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

v7.0 - pin to MEC v7, including matching target frameworks #377

Merged
merged 2 commits into from
May 4, 2023
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
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -428,3 +428,7 @@ In order to make auto-discovery of configuration assemblies work, modify Functio

</Project>
```

### Versioning

This package tracks the versioning and target framework support of its [_Microsoft.Extensions.Configuration_](https://nuget.org/packages/Microsoft.Extensions.Configuration) dependency.
21 changes: 21 additions & 0 deletions sample/Sample/CustomFilter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using Serilog.Core;
using Serilog.Events;

namespace Sample;

// The filter syntax in the sample configuration file is
// processed by the Serilog.Filters.Expressions package.
public class CustomFilter : ILogEventFilter
{
readonly LogEventLevel _levelFilter;

public CustomFilter(LogEventLevel levelFilter = LogEventLevel.Information)
{
_levelFilter = levelFilter;
}

public bool IsEnabled(LogEvent logEvent)
{
return logEvent.Level >= _levelFilter;
}
}
24 changes: 24 additions & 0 deletions sample/Sample/CustomPolicy.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
using System.Diagnostics.CodeAnalysis;
using Serilog.Core;
using Serilog.Events;

namespace Sample;

public class CustomPolicy : IDestructuringPolicy
{
public bool TryDestructure(object value, ILogEventPropertyValueFactory propertyValueFactory, [NotNullWhen(true)] out LogEventPropertyValue? result)
{
result = null;

if (value is LoginData loginData)
{
result = new StructureValue(
new List<LogEventProperty>
{
new("Username", new ScalarValue(loginData.Username))
});
}

return (result != null);
}
}
8 changes: 8 additions & 0 deletions sample/Sample/LoginData.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
namespace Sample;

public class LoginData
{
public string? Username;
// ReSharper disable once NotAccessedField.Global
public string? Password;
}
106 changes: 27 additions & 79 deletions sample/Sample/Program.cs
Original file line number Diff line number Diff line change
@@ -1,98 +1,46 @@
using Microsoft.Extensions.Configuration;

using Sample;
using Serilog;
using Serilog.Core;
using Serilog.Events;
using Serilog.Debugging;

// ReSharper disable UnusedType.Global

namespace Sample;

public class Program
{
public static void Main(string[] args)
{
SelfLog.Enable(Console.Error);

Thread.CurrentThread.Name = "Main thread";

var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: "appsettings.json", optional: false, reloadOnChange: true)
.Build();

var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();

logger.Information("Args: {Args}", 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!");
SelfLog.Enable(Console.Error);

logger.Information("Destructure with max object nesting depth:\n{@NestedObject}",
new { FiveDeep = new { Two = new { Three = new { Four = new { Five = "the end" } } } } });
Thread.CurrentThread.Name = "Main thread";

logger.Information("Destructure with max string length:\n{@LongString}",
new { TwentyChars = "0123456789abcdefghij" });
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: "appsettings.json", optional: false, reloadOnChange: true)
.Build();

logger.Information("Destructure with max collection count:\n{@BigData}",
new { TenItems = new[] { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten" } });
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();

logger.Information("Destructure with policy to strip password:\n{@LoginData}",
new LoginData { Username = "BGates", Password = "isityearoflinuxyet" });
logger.Information("Args: {Args}", args);

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

// The filter syntax in the sample configuration file is
// processed by the Serilog.Filters.Expressions package.
public class CustomFilter : ILogEventFilter
do
{
readonly LogEventLevel _levelFilter;
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!");

public CustomFilter(LogEventLevel levelFilter = LogEventLevel.Information)
{
_levelFilter = levelFilter;
}
logger.Information("Destructure with max object nesting depth:\n{@NestedObject}",
new { FiveDeep = new { Two = new { Three = new { Four = new { Five = "the end" } } } } });

public bool IsEnabled(LogEvent logEvent)
{
return logEvent.Level >= _levelFilter;
}
}
logger.Information("Destructure with max string length:\n{@LongString}",
new { TwentyChars = "0123456789abcdefghij" });

public class LoginData
{
public string? Username;
// ReSharper disable once NotAccessedField.Global
public string? Password;
}

public class CustomPolicy : IDestructuringPolicy
{
public bool TryDestructure(object value, ILogEventPropertyValueFactory propertyValueFactory, out LogEventPropertyValue? result)
{
result = null;
logger.Information("Destructure with max collection count:\n{@BigData}",
new { TenItems = new[] { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten" } });

if (value is LoginData loginData)
{
result = new StructureValue(
new List<LogEventProperty>
{
new("Username", new ScalarValue(loginData.Username))
});
}
logger.Information("Destructure with policy to strip password:\n{@LoginData}",
new LoginData { Username = "BGates", Password = "isityearoflinuxyet" });

return (result != null);
}
Console.WriteLine("\nPress \"q\" to quit, or any other key to run again.\n");
}
while (!args.Contains("--run-once") && (Console.ReadKey().KeyChar != 'q'));
5 changes: 3 additions & 2 deletions sample/Sample/Sample.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFrameworks>net6.0;netcoreapp3.1;net462</TargetFrameworks>
<TargetFrameworks>net6.0;net7.0;net462</TargetFrameworks>
<OutputType>Exe</OutputType>
</PropertyGroup>

Expand All @@ -14,14 +14,15 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" />
<PackageReference Include="Serilog.Sinks.Async" Version="1.5.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="4.0.1" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
<PackageReference Include="Serilog.Enrichers.Environment" Version="2.2.0" />
<PackageReference Include="Serilog.Expressions" Version="3.3.0" />
<PackageReference Include="Serilog.Formatting.Compact" Version="1.1.0" />
<PackageReference Include="Serilog.Enrichers.Thread" Version="3.1.0" />
<PackageReference Include="PolySharp" Version="1.13.1" PrivateAssets="all" />
</ItemGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -228,20 +228,20 @@ public static LoggerConfiguration Configuration(
static ConfigurationReader GetConfigurationReader(IConfiguration configuration, ConfigurationReaderOptions readerOptions, DependencyContext? dependencyContext)
{
var assemblyFinder = dependencyContext == null ? AssemblyFinder.Auto() : AssemblyFinder.ForDependencyContext(dependencyContext);
var section = string.IsNullOrWhiteSpace(readerOptions.SectionName) ? configuration : configuration.GetSection(readerOptions.SectionName);
var section = string.IsNullOrWhiteSpace(readerOptions.SectionName) ? configuration : configuration.GetSection(readerOptions.SectionName!);
return new ConfigurationReader(section, assemblyFinder, readerOptions, configuration);
}

static ConfigurationReader GetConfigurationReader(IConfiguration configuration, ConfigurationReaderOptions readerOptions, ConfigurationAssemblySource source)
{
var assemblyFinder = AssemblyFinder.ForSource(source);
var section = string.IsNullOrWhiteSpace(readerOptions.SectionName) ? configuration : configuration.GetSection(readerOptions.SectionName);
var section = string.IsNullOrWhiteSpace(readerOptions.SectionName) ? configuration : configuration.GetSection(readerOptions.SectionName!);
return new ConfigurationReader(section, assemblyFinder, readerOptions, configuration);
}

static ConfigurationReader GetConfigurationReader(IConfiguration configuration, ConfigurationReaderOptions readerOptions, IReadOnlyCollection<Assembly> assemblies)
{
var section = string.IsNullOrWhiteSpace(readerOptions.SectionName) ? configuration : configuration.GetSection(readerOptions.SectionName);
var section = string.IsNullOrWhiteSpace(readerOptions.SectionName) ? configuration : configuration.GetSection(readerOptions.SectionName!);
return new ConfigurationReader(section, assemblies, new ResolutionContext(configuration, readerOptions));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@

<PropertyGroup>
<Description>Microsoft.Extensions.Configuration (appsettings.json) support for Serilog.</Description>
<VersionPrefix>4.0.0</VersionPrefix>
<!-- This must match the major and minor components of the referenced Microsoft.Extensions.Logging package. -->
<VersionPrefix>7.0.0</VersionPrefix>
<Authors>Serilog Contributors</Authors>
<TargetFrameworks>netstandard2.0;net461</TargetFrameworks>
<!-- These must match the Dependencies tab in https://www.nuget.org/packages/microsoft.settings.configuration at
the target version. -->
<TargetFrameworks>net462;netstandard2.0;net6.0;net7.0</TargetFrameworks>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<AssemblyName>Serilog.Settings.Configuration</AssemblyName>
<PackageTags>serilog;json</PackageTags>
Expand All @@ -23,11 +26,14 @@

<ItemGroup>
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyModel" Version="6.0.0" />
<PackageReference Include="PolySharp" Version="1.12.1" PrivateAssets="All" />
<PackageReference Include="Serilog" Version="2.10.0" />
<PackageReference Include="PolySharp" Version="1.13.1" PrivateAssets="All" />
<PackageReference Include="Serilog" Version="2.12.0" />
<None Include="..\..\assets\icon.png" Pack="true" PackagePath="" Visible="false" />
</ItemGroup>

<ItemGroup>
<!-- The versions of all references in this group must match the major and minor components of the package version prefix. -->
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyModel" Version="7.0.0" />
</ItemGroup>
</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ void ProcessLevelSwitchDeclarations()
}
else
{
var initialLevel = ParseLogEventLevel(switchInitialLevel);
var initialLevel = ParseLogEventLevel(switchInitialLevel!);
newSwitch = new LoggingLevelSwitch(initialLevel);
}

Expand Down Expand Up @@ -171,17 +171,17 @@ void ApplyMinimumLevel(LoggerConfiguration loggerConfiguration)
_resolutionContext.ReaderOptions.OnLevelSwitchCreated?.Invoke(overridePrefix, levelSwitch);
});
}
else
else if (!string.IsNullOrEmpty(overridenLevelOrSwitch))
{
var overrideSwitch = _resolutionContext.LookUpLevelSwitchByName(overridenLevelOrSwitch);
var overrideSwitch = _resolutionContext.LookUpLevelSwitchByName(overridenLevelOrSwitch!);
// not calling ApplyMinimumLevel local function because here we have a reference to a LogLevelSwitch already
loggerConfiguration.MinimumLevel.Override(overridePrefix, overrideSwitch);
}
}

void ApplyMinimumLevelConfiguration(IConfigurationSection directive, Action<LoggerMinimumLevelConfiguration, LoggingLevelSwitch> applyConfigAction)
{
var minimumLevel = ParseLogEventLevel(directive.Value);
var minimumLevel = ParseLogEventLevel(directive.Value!);

var levelSwitch = new LoggingLevelSwitch(minimumLevel);
applyConfigAction(loggerConfiguration.MinimumLevel, levelSwitch);
Expand Down Expand Up @@ -293,7 +293,8 @@ void ApplyEnrichment(LoggerConfiguration loggerConfiguration)
{
foreach (var enrichPropertyDirective in propertiesDirective.GetChildren())
{
loggerConfiguration.Enrich.WithProperty(enrichPropertyDirective.Key, enrichPropertyDirective.Value);
// Null is an acceptable value here; annotations on Serilog need updating.
Copy link
Contributor

Choose a reason for hiding this comment

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

loggerConfiguration.Enrich.WithProperty(enrichPropertyDirective.Key, enrichPropertyDirective.Value!);
}
}
}
Expand Down Expand Up @@ -359,7 +360,7 @@ internal static IConfigurationArgumentValue GetArgumentValue(IConfigurationSecti
static IReadOnlyCollection<Assembly> LoadConfigurationAssemblies(IConfiguration section, AssemblyFinder assemblyFinder)
{
var serilogAssembly = typeof(ILogger).Assembly;
var assemblies = new Dictionary<string, Assembly> { [serilogAssembly.FullName] = serilogAssembly };
var assemblies = new Dictionary<string, Assembly> { [serilogAssembly.FullName!] = serilogAssembly };

var usingSection = section.GetSection("Using");
if (usingSection.GetChildren().Any())
Expand All @@ -371,16 +372,16 @@ static IReadOnlyCollection<Assembly> LoadConfigurationAssemblies(IConfiguration
"A zero-length or whitespace assembly name was supplied to a Serilog.Using configuration statement.");

var assembly = Assembly.Load(new AssemblyName(simpleName));
if (!assemblies.ContainsKey(assembly.FullName))
assemblies.Add(assembly.FullName, assembly);
if (!assemblies.ContainsKey(assembly.FullName!))
assemblies.Add(assembly.FullName!, assembly);
}
}

foreach (var assemblyName in assemblyFinder.FindAssembliesContainingName("serilog"))
{
var assumed = Assembly.Load(assemblyName);
if (assumed != null && !assemblies.ContainsKey(assumed.FullName))
assemblies.Add(assumed.FullName, assumed);
if (assumed != null && !assemblies.ContainsKey(assumed.FullName!))
assemblies.Add(assumed.FullName!, assumed);
}

return assemblies.Values.ToList().AsReadOnly();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ internal static bool TryBuildCtorExpression(

var type = typeDirective switch
{
not null => Type.GetType(section.GetValue<string>(typeDirective), throwOnError: false),
not null => Type.GetType(section.GetValue<string>(typeDirective)!, throwOnError: false),
null => parameterType,
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -189,10 +189,10 @@ public void MethodsAreSelectedBasedOnCountOfMatchedArgumentsAndThenStringType()
{
new object[] { GetConfigRoot(appsettingsJsonLevel: minimumLevelFlatTemplate.Format(LogEventLevel.Error)), LogEventLevel.Error },
new object[] { GetConfigRoot(appsettingsDevelopmentJsonLevel: minimumLevelFlatTemplate.Format(LogEventLevel.Error)), LogEventLevel.Error },
new object[] { GetConfigRoot(envVariables: new Dictionary<string, string>() {{minimumLevelFlatKey, LogEventLevel.Error.ToString()}}), LogEventLevel.Error},
new object[] { GetConfigRoot(envVariables: new Dictionary<string, string?> {{minimumLevelFlatKey, LogEventLevel.Error.ToString()}}), LogEventLevel.Error},
new object[] { GetConfigRoot(
appsettingsJsonLevel: minimumLevelFlatTemplate.Format(LogEventLevel.Debug),
envVariables: new Dictionary<string, string>() {{minimumLevelFlatKey, LogEventLevel.Error.ToString()}}),
envVariables: new Dictionary<string, string?> {{minimumLevelFlatKey, LogEventLevel.Error.ToString()}}),
LogEventLevel.Error
}
};
Expand All @@ -214,7 +214,7 @@ public void FlatMinimumLevelCorrectOneIsEnabledOnLogger(IConfigurationRoot root,
new object[] { GetConfigRoot(appsettingsJsonLevel: minimumLevelObjectTemplate.Format(LogEventLevel.Error)), LogEventLevel.Error },
new object[] { GetConfigRoot(appsettingsJsonLevel: minimumLevelObjectTemplate.Format(LogEventLevel.Error.ToString().ToUpper())), LogEventLevel.Error },
new object[] { GetConfigRoot(appsettingsDevelopmentJsonLevel: minimumLevelObjectTemplate.Format(LogEventLevel.Error)), LogEventLevel.Error },
new object[] { GetConfigRoot(envVariables: new Dictionary<string, string>(){{minimumLevelObjectKey, LogEventLevel.Error.ToString() } }), LogEventLevel.Error },
new object[] { GetConfigRoot(envVariables: new Dictionary<string, string?>{{minimumLevelObjectKey, LogEventLevel.Error.ToString() } }), LogEventLevel.Error },
new object[] { GetConfigRoot(
appsettingsJsonLevel: minimumLevelObjectTemplate.Format(LogEventLevel.Error),
appsettingsDevelopmentJsonLevel: minimumLevelObjectTemplate.Format(LogEventLevel.Debug)),
Expand Down Expand Up @@ -254,7 +254,7 @@ public void ObjectMinimumLevelCorrectOneIsEnabledOnLogger(IConfigurationRoot roo
new object[]
{
GetConfigRoot(
envVariables: new Dictionary<string, string>()
envVariables: new Dictionary<string, string?>()
{
{minimumLevelObjectKey, LogEventLevel.Error.ToString()},
{minimumLevelFlatKey, LogEventLevel.Debug.ToString()}
Expand Down
Loading