refactor: Add exception message enricher

Allows exception message without a stack trace to be written to the
console, while full exception details are still written to file sinks.
pull/201/head
Robert Dailey 2 years ago
parent 684128968c
commit 64306db2dc

@ -1,4 +1,5 @@
using System.IO.Abstractions;
using Recyclarr.Common.Serilog;
using Recyclarr.TrashLib.Startup;
using Serilog;
using Serilog.Events;
@ -22,19 +23,20 @@ public class LoggerFactory
return
$"{{#if {scope} is not null}}{{{scope}}}: {{#end}}" +
"{@m}\n" +
"{@x}";
"{@m}";
}
private static ExpressionTemplate GetConsoleTemplate()
{
var template = "[{@l:u3}] " + GetBaseTemplateString();
var template = "[{@l:u3}] " + GetBaseTemplateString() + ": {ExceptionMessage}\n";
return new ExpressionTemplate(template, theme: TemplateTheme.Code);
}
private static ExpressionTemplate GetFileTemplate()
{
var template = "[{@t:HH:mm:ss} {@l:u3}] " + GetBaseTemplateString();
var template = "[{@t:HH:mm:ss} {@l:u3}] " + GetBaseTemplateString() + "\n{@x}";
return new ExpressionTemplate(template);
}
@ -44,6 +46,7 @@ public class LoggerFactory
return new LoggerConfiguration()
.MinimumLevel.Is(LogEventLevel.Debug)
.Enrich.With<ExceptionMessageEnricher>()
.WriteTo.Console(GetConsoleTemplate(), level)
.WriteTo.File(GetFileTemplate(), logPath.FullName)
.Enrich.FromLogContext()

@ -0,0 +1,18 @@
using Serilog.Core;
using Serilog.Events;
namespace Recyclarr.Common.Serilog;
public class ExceptionMessageEnricher : ILogEventEnricher
{
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
{
if (logEvent.Exception is null)
{
return;
}
logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty(
"ExceptionMessage", logEvent.Exception.Message));
}
}
Loading…
Cancel
Save