# Serilog Enricher for exceptions

**URL:** <https://forum.umbraco.com/t/serilog-enricher-for-exceptions/5754>\
**Category:** Questions\
**Tags:** v13\
**Created:** [September 9, 2025, 8:20am UTC](https://forum.umbraco.com/t/serilog-enricher-for-exceptions/5754 "2025-09-09T08:20:39Z")\
**Posts on this page:** 11\
**Page:** 1

<div class="post-metadata">

**Author:** ![markusjoha](https://forum.umbraco.com/user_avatar/forum.umbraco.com/markusjoha/32/141_2.png) [@markusjoha](https://forum.umbraco.com/u/markusjoha)\
**Post date:** [September 9, 2025, 8:20am UTC](https://forum.umbraco.com/t/serilog-enricher-for-exceptions/5754/1 "2025-09-09T08:20:39Z")

</div>

Hi!

I’m trying to add some additional properties to the log messages produced when a exception is logged by Serilog.

I’ve tried adding a middleware and use the same approach as the core request logging middleware (push in new enrichers using `LogContext.Push`). It works great for things “inside” the request, like controllers etc. But, it seems like this scope is disposed before the unhandled exception logging kicks in, so these enrichers are not called when the exception is logged.

I’ve looked around for ways to define additional enrichers, but it seems like they are all hardcoded in an extension method.

Anyone who successfully managed to add custom enrichers for exceptions?

---

<div class="post-metadata">

**Author:** ![mistyn8](https://forum.umbraco.com/user_avatar/forum.umbraco.com/mistyn8/32/671_2.png) [@mistyn8](https://forum.umbraco.com/u/mistyn8)\
**Post date:** [September 9, 2025, 10:08am UTC](https://forum.umbraco.com/t/serilog-enricher-for-exceptions/5754/2 "2025-09-09T10:08:45Z")

</div>

Any pointers here?

> **[GitHub - RehanSaeed/Serilog.Exceptions: Log exception details and custom properties that...](https://github.com/RehanSaeed/Serilog.Exceptions)**
>
> Log exception details and custom properties that are not output in Exception.ToString().

---

<div class="post-metadata">

**Author:** ![markusjoha](https://forum.umbraco.com/user_avatar/forum.umbraco.com/markusjoha/32/141_2.png) [@markusjoha](https://forum.umbraco.com/u/markusjoha)\
**Post date:** [September 12, 2025, 12:00pm UTC](https://forum.umbraco.com/t/serilog-enricher-for-exceptions/5754/3 "2025-09-12T12:00:25Z")

</div>

Thanks for trying @mistyn8, I’m quite happy with the way that exceptions are logged, my problem was that I needed to use my own custom enricher(s).

As far as I understand. Umbraco calls `.Enrich.FromLogContext()` during Serilog setup as a way to allow for adding custom enrichers. The problem is that these are scoped to the current LogContext, and when an unhandled exception happens, this scope is disposed. This means that any “per-request”-registered enrichers will not run. E.g. the built-in ones in Umbraco like SessionIdEnricher, RequestNumberEnricher, and RequestIdEnricher will not run for unhandled exceptions.

The only way (that I’ve found) to get around this without updating the source of Umbraco is to use `appsettings.json`to register the enricher in the Serilog-section.

```auto
"Using": ["MyProject.Web"],
"Enrich": [
  { "Name": "WithMyCustomEnrichers" }
]

```

Then have an extension method in `MyProject.Web`namespace like so:

```auto
public static LoggerEnrichmentConfiguration WithMyCustomEnrichers(
    this LoggerEnrichmentConfiguration enrichmentConfiguration)
{
    if (enrichmentConfiguration == null)
        throw new ArgumentNullException(nameof(enrichmentConfiguration));

    // Notice: No idea trying to use StaticServiceProvider.Instance as it will be null.
    // because this method is called before the service provider is built.

    enrichmentConfiguration.With<RequestUserAgentEnricher>();

    return enrichmentConfiguration;

}

```

The enrichers need to have a parameterless constructor. If you need access to DI you’d have to use `StaticServiceProvider.Instance ` to get access to “stuff” from DI. A good option is to use Lazy properties for this.

---

<div class="post-metadata">

**Author:** ![mistyn8](https://forum.umbraco.com/user_avatar/forum.umbraco.com/mistyn8/32/671_2.png) [@mistyn8](https://forum.umbraco.com/u/mistyn8)\
**Post date:** [September 12, 2025, 12:40pm UTC](https://forum.umbraco.com/t/serilog-enricher-for-exceptions/5754/4 "2025-09-12T12:40:15Z")

</div>

Sorry completely off the mark with your question..  
Though could [GitHub - serilog-contrib/serilog-enrichers-globallogcontext: A Serilog Enricher for adding properties to all log events in your app](https://github.com/serilog-contrib/serilog-enrichers-globallogcontext) be of use?

and perplexity gave this with a little prompting.. to add your enricher in code, rather than appsettings.. ???

```auto
public class SerilogEnricherComposer : IComposer
{
    public void Compose(IUmbracoBuilder builder)
    {
        // Extend the existing Serilog logger by adding the custom enricher
        Log.Logger = new LoggerConfiguration()
            .ReadFrom.Logger(Log.Logger) // inherit existing configuration
            .Enrich.With<WithMyCustomEnricher>() // add your custom enricher
            .CreateLogger();
    }
}

```

and another thought

```auto
// note umbraco logViewer expects string not json so won't show destructured.. but seq should
var scopeProps = new Dictionary<string, object> {
    { "@Model", model },
};
 using (_logger.BeginScope(scopeProps))
 {
     _logger.LogInformation("Account register: {Email} registering for a new account", model.ContactDetails.Email);
}

```

to use the MSLogger abstraction rather than serilog specific?

> **[The semantics of ILogger.BeginScope()](https://nblumhardt.com/2016/11/ilogger-beginscope/)**
>
> Microsoft.Extensions.Logging’s ILogger adds context to log events with BeginScope():

Also there is the IDiagnosticContext, to make things less chatty and squash a request down to a single log entry…

> **[GitHub - serilog/serilog-aspnetcore: Serilog integration for ASP.NET Core](https://github.com/serilog/serilog-aspnetcore?tab=readme-ov-file#request-logging)**
>
> Serilog integration for ASP.NET Core

not sure if that combines scopes and would perists your log context for exceptions though 🤔

---

<div class="post-metadata">

**Author:** ![mistyn8](https://forum.umbraco.com/user_avatar/forum.umbraco.com/mistyn8/32/671_2.png) [@mistyn8](https://forum.umbraco.com/u/mistyn8)\
**Post date:** [September 12, 2025, 12:54pm UTC](https://forum.umbraco.com/t/serilog-enricher-for-exceptions/5754/5 "2025-09-12T12:54:54Z")

</div>

Also found this I was messing around with.. can’t remember if it worked or not for DI…

```auto
using Microsoft.AspNetCore.Http;
using Serilog.Core;
using Serilog.Events;

namespace www.Code.Extensions.Logging
{

    public class LovellEnricher : ILogEventEnricher
    {
        private readonly IHttpContextAccessor _contextAccessor;

        public LovellEnricher()
            : this(new HttpContextAccessor())
        {
        }

        internal LovellEnricher(IHttpContextAccessor contextAccessor)
        {
            _contextAccessor = contextAccessor;
        }

        public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
        {
            var httpContext = _contextAccessor.HttpContext;
            if (httpContext == null)
            {
                return;
            }
// do we have httpContext?

       }
   }
}

```

Looking at it prob not.. think this was the source for the experiment…

> **[Injecting services into Serilog filters, enrichers, and sinks](https://nblumhardt.com/2020/09/serilog-inject-dependencies/)**
>
> Hey! 👋 You might have missed a change that snuck quietly into Serilog.AspNetCore and Serilog.Extensions.Hosting just recently. It’s now a lot easier to injec...

> **[Bootstrap logging with Serilog + ASP.NET Core](https://nblumhardt.com/2020/10/bootstrap-logger/)**
>
> Errors during application start-up are some of the nastiest problems to hit in production. Deployment issues like broken manifests or missing assemblies, inc...

---

<div class="post-metadata">

**Author:** ![markusjoha](https://forum.umbraco.com/user_avatar/forum.umbraco.com/markusjoha/32/141_2.png) [@markusjoha](https://forum.umbraco.com/u/markusjoha)\
**Post date:** [September 15, 2025, 2:19pm UTC](https://forum.umbraco.com/t/serilog-enricher-for-exceptions/5754/6 "2025-09-15T14:19:58Z")

</div>

Thanks @mistyn8!

I did spend about 4 hours trying to get something to work for **unhandled exception**.

About your examples:

1. 

```auto
.Enrich.FromGlobalLogContext()

```

Not an option as it would require me to reconfigure the logger that Umbraco uses, which feels “overkill” just to be able to add an enricher.

If I were to replace the logging initialization, it would be easy to just add my enrichers like so

```auto
.Enrich.With<MyCustomEnricher>()

```

1. 

```auto
using (_logger.BeginScope(scopeProps))
{
     _logger.LogInformation("Account register: {Email} registering for a new account", model.ContactDetails.Email);
}

```

Since I do not control the code that performs the logging (it’s part of Serilog) I cannot create a new scope when unhandled exceptions are logged.

1. 

```auto
LovellEnricher : ILogEventEnricher

```

Yes, this is what I’m doing. The problem was never to implement the enricher but to get it to fire for unhandled exceptions.

If you have a working sample on how to add a custom enricher that runs on unhandled exceptions without replacing the default i logger declaration, it would be cool to see 😀

I’ve got a workaround that works, so I’m quite happy. But it would be nice if there were a hook to register enrichers during the setup.

---

<div class="post-metadata">

**Author:** ![mistyn8](https://forum.umbraco.com/user_avatar/forum.umbraco.com/mistyn8/32/671_2.png) [@mistyn8](https://forum.umbraco.com/u/mistyn8)\
**Post date:** [September 16, 2025, 11:02am UTC](https://forum.umbraco.com/t/serilog-enricher-for-exceptions/5754/7 "2025-09-16T11:02:07Z")

</div>

So I don’t think that you do have to reinitialise the logger…

From the last article link…

> Spot the difference? CreateBootstrapLogger() returns a new, mutable logger type, ReloadableLogger, that can be reconfigured on-the-fly.
> 
> The callback overload of UseSerilog() is aware of this: if Log.Logger is a ReloadableLogger, it will be reconfigured through the callback, and then “frozen” into the efficient, immutable logging pipeline that the application will use for the remainder of its execution time.

> <https://github.com/umbraco/Umbraco-CMS/blob/ef1aaf8bcea3fb8144c2b82959678fa401b1ea58/src/Umbraco.Web.Common/Extensions/ServiceCollectionExtensions.cs#L61-L68>

So that to me looks like, if you create a reloadable logger earlier than umbraco with createBootstrapLogger, then Umbraco will add it’s config to it.. or if you alter the config via the UseSerilog() callback after umbraco then it too will add to the configuration..

Also the original example though not sure required now with the newer boostrapping.. had  
`.ReadFrom.Logger(Log.Logger) // inherit existing configuration`  
so even though reinitialising it should bring all the existing configuration??

---

<div class="post-metadata">

**Author:** ![mistyn8](https://forum.umbraco.com/user_avatar/forum.umbraco.com/mistyn8/32/671_2.png) [@mistyn8](https://forum.umbraco.com/u/mistyn8)\
**Post date:** [September 16, 2025, 11:03am UTC](https://forum.umbraco.com/t/serilog-enricher-for-exceptions/5754/8 "2025-09-16T11:03:10Z")

</div>

Had a play with the globalLogContext.. and can see new props in errors logged to serilog…

 ![image](https://forum.umbraco.com/uploads/default/original/2X/e/e70cbb0f0a20d791649b7ddb212fb364219da105.png)  
 ![image](https://forum.umbraco.com/uploads/default/original/2X/c/c120e2bc9bca94b724873092c4f4151d334441d8.png)  
 ![image](https://forum.umbraco.com/uploads/default/original/2X/6/60971be5c64f6321a9118715eea5b81bc53f74b1.png)  
 ![image](https://forum.umbraco.com/uploads/default/original/2X/3/39bb4267281051181a05d45c8f2f9c786adb7cb6.png)

---

<div class="post-metadata">

**Author:** ![markusjoha](https://forum.umbraco.com/user_avatar/forum.umbraco.com/markusjoha/32/141_2.png) [@markusjoha](https://forum.umbraco.com/u/markusjoha)\
**Post date:** [September 16, 2025, 12:14pm UTC](https://forum.umbraco.com/t/serilog-enricher-for-exceptions/5754/9 "2025-09-16T12:14:29Z")

</div>

Interesting @mistyn8 😀

I’ll try to see if it’s possible to append to `GlobalLogContext` during startup, it would be nice to avoid having to fiddle with appSettings to get the enrichers configured.

I’ll share any progress if I find a better approach than the one I posted initially.

Cheers!

// m

---

<div class="post-metadata">

**Author:** ![mistyn8](https://forum.umbraco.com/user_avatar/forum.umbraco.com/mistyn8/32/671_2.png) [@mistyn8](https://forum.umbraco.com/u/mistyn8)\
**Post date:** [September 16, 2025, 12:16pm UTC](https://forum.umbraco.com/t/serilog-enricher-for-exceptions/5754/10 "2025-09-16T12:16:44Z")

</div>

FYI [GitHub - serilog/serilog-aspnetcore: Serilog integration for ASP.NET Core](https://github.com/serilog/serilog-aspnetcore?tab=readme-ov-file#request-logging)

To make serilog less chatty and squash logs related to a single request down to one log event..

this series is wonderful!

> **[Logging MVC properties with Serilog.AspNetCore: Using Serilog.AspNetCore in...](https://andrewlock.net/using-serilog-aspnetcore-in-asp-net-core-3-logging-mvc-propertis-with-serilog/)**
>
> In this post I show how to log MVC-specific properties like ActionName or RazorPage HandlerName when using Serilog.AspNetCore's request logging middleware

Maybe something like..

```csharp
using Microsoft.AspNetCore.Mvc.Filters;
using Serilog;
using Umbraco.Cms.Core.Composing;
using Umbraco.Cms.Core.Sync;
using Umbraco.Cms.Web.Common.ApplicationBuilder;

namespace www.Code.Extensions.Logging
{
    public static class WwwRequestLoggingOptions
    {
        public static void EnrichFromRequest(IDiagnosticContext diagnosticContext, HttpContext httpContext)
        {
            var request = httpContext.Request;

            // Set all the common properties available for every request
            diagnosticContext.Set("RequestHost", request.Host);

            // Only set it if available. You're not sending sensitive data in a querystring right?!
            if (request.QueryString.HasValue)
            {
                diagnosticContext.Set("RequestQueryString", request.QueryString.Value);
            }

            // Set the content-type of the Response at this point
            diagnosticContext.Set("RequestContentType", httpContext?.Response?.ContentType ?? "n/a");

            // Retrieve the IEndpointFeature selected for the request
            var endpoint = httpContext.GetEndpoint();
            if (endpoint is object) // endpoint != null
            {
                diagnosticContext.Set("RequestEndpointName", endpoint.DisplayName ?? "n/a");
            }
        }
    }

    public class SerilogExceptionEnricherMvcFilter : IExceptionFilter
    {
        public void OnException(ExceptionContext context)
        {
            var dc = context.HttpContext.RequestServices.GetRequiredService<IDiagnosticContext>();
            dc.SetException(context.Exception);
        }
    }

    public class SerilogLoggingActionFilter : IActionFilter
    {
        private readonly IDiagnosticContext _diagnosticContext;
        private readonly IServerRoleAccessor _serverRoleAccessor;

        public SerilogLoggingActionFilter(IDiagnosticContext diagnosticContext, IServerRoleAccessor serverRoleAccessor)
        {
            _diagnosticContext = diagnosticContext;
            _serverRoleAccessor = serverRoleAccessor;
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            _diagnosticContext.Set("RouteData", context.ActionDescriptor.RouteValues);
            _diagnosticContext.Set("ActionName", context.ActionDescriptor.DisplayName ?? "n/a");
            _diagnosticContext.Set("ActionId", context.ActionDescriptor.Id);
            _diagnosticContext.Set("ValidationState", context.ModelState.IsValid);
            _diagnosticContext.Set("UmbracoServerRole", _serverRoleAccessor.CurrentServerRole);
        }

        // Required by the interface
        public void OnActionExecuted(ActionExecutedContext context) { }

        public class SerilogRequestLoggingComposer : IComposer
        {
            // can move to prePipeline if we want to log static files.
            // in 13.1.1 can move to preRouting for just after static files 
            public void Compose(IUmbracoBuilder builder)
            {
                builder.Services.Configure<Microsoft.AspNetCore.Mvc.MvcOptions>(options =>
                {
                    options.Filters.Add<SerilogExceptionEnricherMvcFilter>();
                });

                builder.Services.AddControllers(opts => opts.Filters.Add<SerilogLoggingActionFilter>());
                builder.Services.Configure<UmbracoPipelineOptions>(options =>
                {
                    options.AddFilter(
                        new UmbracoPipelineFilter("SerilogRequestLogging",
                            prePipeline: null,
                            preRouting: null,
                            postRouting: null,
                            postPipeline: app => app.UseSerilogRequestLogging(opt => opt.EnrichDiagnosticContext = LovellRequestLoggingOptions.EnrichFromRequest),
                            endpoints: null
                        )
                    );
                });
            }
        }
    }

}

```

---

<div class="post-metadata">

**Author:** ![system](https://forum.umbraco.com/uploads/default/original/1X/624adeddd330a3d0268a184db47946ca7e82c676.png) [@system](https://forum.umbraco.com/u/system)\
**Post date:** [October 16, 2025, 12:17pm UTC](https://forum.umbraco.com/t/serilog-enricher-for-exceptions/5754/11 "2025-10-16T12:17:09Z")

</div>

Closed on October 16, 2025, 12:17pm UTC

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.
