Skip to content

Instantly share code, notes, and snippets.

@PureKrome
Last active June 14, 2023 13:49
Show Gist options
  • Save PureKrome/53e12d145e9ff14e231ac8e59c2bc3a8 to your computer and use it in GitHub Desktop.
Save PureKrome/53e12d145e9ff14e231ac8e59c2bc3a8 to your computer and use it in GitHub Desktop.
Logging to the console with .NET 7 + top level statements + Serilog + custom logging extension method
/*
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.1" />
<PackageReference Include="Serilog.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="Serilog.Formatting.Compact" Version="1.1.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="4.1.0" />
</ItemGroup>
*/
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Formatting.Compact;
Log.Logger = new LoggerConfiguration()
.WriteTo.Console(new CompactJsonFormatter()) // See all the scoped items.
.WriteTo.Console() // See a human readable line
.CreateLogger();
ILoggerFactory loggerFactory = new LoggerFactory()
.AddSerilog();
var logger = loggerFactory.CreateLogger<Program>();
string subscriptionId = "ABC123";
using var _ = logger.BeginScopeCustom(subscriptionId);
logger.LogInformation("This is a log message with subscriptionId {SubscriptionId}", subscriptionId);
// REF: https://andrewlock.net/using-anonymous-types-and-tuples-to-attach-correlation-ids-to-scope-state-with-serilog-and-seq-in-asp-net-core/
public static class LoggerExtensions
{
public static IDisposable? BeginScopeCustom(this ILogger logger, object input) =>
logger.BeginScopeCustom(nameof(input), input);
public static IDisposable? BeginScopeCustom(this ILogger logger, string key, object value) =>
logger.BeginScope(new Dictionary<string, object> { { key, value } });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment