Serilog.ThrowContext 0.1.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package Serilog.ThrowContext --version 0.1.0
NuGet\Install-Package Serilog.ThrowContext -Version 0.1.0
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Serilog.ThrowContext" Version="0.1.0" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Serilog.ThrowContext --version 0.1.0
#r "nuget: Serilog.ThrowContext, 0.1.0"
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install Serilog.ThrowContext as a Cake Addin
#addin nuget:?package=Serilog.ThrowContext&version=0.1.0

// Install Serilog.ThrowContext as a Cake Tool
#tool nuget:?package=Serilog.ThrowContext&version=0.1.0

Throw context enricher for Serilog Azure DevOps tests

Captures LogContext of a thrown exception to enrich logs when the exception is eventually logged.

Use case

Assume an exception is thrown in scope with context properties:

[HttpGet()]
public WeatherForecast Get()
{
    var rng = new Random();
    using (LogContext.PushProperty("WeatherForecast", new
    {
        Date = DateTime.Now.AddDays(1),
        TemperatureC = rng.Next(-20, 55),
        Summary = Summaries[rng.Next(Summaries.Length)]
    }))
    {
        throw new Exception("Oops");
    }
}

If the exception is caught and logged outside the scope, context properties are lost by default.

// global exception handler middleware
app.Use(async (context, next) =>
{
    try
    {
        await next();
    }
    catch (Exception ex)
    {
        log.LogError(ex, "Exceptional weather"); // would not contain WeatherForecast property`
    }
});

Installation

It is possible to register ThrowContextEnricher globally or just to use once in a specific exception handler.

Global enricher

Just add .Enrich.With<ThrowContextEnricher>():

Log.Logger = new LoggerConfiguration()
    .Enrich.With<ThrowContextEnricher>()
    .Enrich.FromLogContext()
    .WriteTo
    ...
    .CreateLogger();

Note that order of ThrowContextEnricher and Serilog's LogContextEnricher matters when a property exists both in exception's origin and handler contexts:

<table> <tr> <td> <pre lang="c#"> Log.Logger = new LoggerConfiguration() .Enrich.With<ThrowContextEnricher>() .Enrich.FromLogContext() ... </pre> </td> <td> <pre lang="c#"> Log.Logger = new LoggerConfiguration() .Enrich.FromLogContext() .Enrich.With<ThrowContextEnricher>() ... </pre>
</tr> <tr> <td colspan="2"> <pre lang="c#"> using (LogContext.PushProperty("A", "outer")) try { using (LogContext.PushProperty("A", "inner")) throw new Exception(); } catch (Exception ex) { Log.Error(ex, "Value of A is {A}"); } </pre> </td> </tr> <tr> <td>Exception's value is used (A="inner")</td> <td>Handler's value is used (A="outer")</td> </tr> </table>

Local enricher

It is also possible to enrich only specific log rather registering the enricher globally:

Log.Logger = new LoggerConfiguration()
    .Enrich.FromLogContext()
    ...
    .CreateLogger();

ThrowContextEnricher.EnsureInitialized();

...
using (LogContext.PushProperty("A", "outer"))
    try
    {
        using (LogContext.PushProperty("A", "inner"))
        {
            throw new Exception();
        }

    }
    catch (Exception ex)
    {
        using (LogContext.Push(new ThrowContextEnricher()))
        {
            Log.Error(ex, "Value of A is {A}"); // "Value of A is \"inner\""
        }
    }

Note ThrowContextEnricher.EnsureInitialized() is used to trigger ThrowContextEnricher' static ctor to begin capturing properties. If this call is omitted, enricher may be lazily initialized only in an exception handler, thus the first occurred exception would miss properties.

Rethrow

If an exception is rethrown in a different context, the origin property value is not overwritten:

Log.Logger = new LoggerConfiguration()
    .Enrich.With<ThrowContextEnricher>()
    .Enrich.FromLogContext()
    .WriteTo.Console(new RenderedCompactJsonFormatter())
    .CreateLogger();

try
{
    try
    {
        using (LogContext.PushProperty("A", 1))
            throw new ApplicationException();
    }
    catch
    {
        using (LogContext.PushProperty("A", 2))
        using (LogContext.PushProperty("B", 2))
            throw;
    }
}
catch (ApplicationException ex)
{
    Log.Information(ex, "A={A}, B={B}"); // "A=1, B=2"
}

Wrap

If an exception is wrapped into another in a different context, the wrapper context is used. Log of inner exception produces origin value though.

Log.Logger = new LoggerConfiguration()
    .Enrich.With<ThrowContextEnricher>()
    .Enrich.FromLogContext()
    .WriteTo.Console(new RenderedCompactJsonFormatter())
    .CreateLogger();

try
{
    try
    {
        using (LogContext.PushProperty("A", 1))
            throw new Exception();
    }
    catch (Exception ex)
    {
        using (LogContext.PushProperty("A", 2))
        using (LogContext.PushProperty("B", 2))
            throw new ApplicationException("Wrapper", ex);
    }
}
catch (ApplicationException ex)
{
    Log.Information(ex, "A={A}, B={B}"); // "A=2, B=2"
    Log.Information(ex.InnerException, "A={A}, B={B}"); // "A=1, B={B}"
}
Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • .NETStandard 2.0

NuGet packages (1)

Showing the top 1 NuGet packages that depend on Serilog.ThrowContext:

Package Downloads
Koala.Newtonsoft.Json

Koala.Serialization is a library contains extensions to take maximum out of Newtonsoft Json

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
0.1.2 639,275 3/16/2020
0.1.1 451 3/16/2020
0.1.0 32,802 3/15/2020