Serilog custom exception message

203 Views Asked by At

My current task : I need to remove StackTrace from {Exception} object in OutputTemplate

"WriteTo": [
      {
        "Name": "Console",
        "Args": {
          "outputTemplate": "[{Timestamp:yyyy:MM:dd hh:mm:ss} {CorrelationId} {Level:u3}] {Message:lj}{NewLine}{Exception}"
        }
      }]

Exception object contains Message AND StackTrace. I need to remove StackTrace. Is it possible?

I have tried custom property inside custom Enricher:

public class ExceptionEnricherTest : ILogEventEnricher
     {
          public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
          {
              if (logEvent.Exception == null)
              {
                  return;
              }
    
         var logEventProperty = propertyFactory.CreateProperty("ExceptionWithoutStackTrace", logEvent.Exception.Message);
    
            logEvent.AddPropertyIfAbsent(logEventProperty);
          }
     }
public static class LoggingExtensions
    {
        public static LoggerConfiguration WithExceptionEnricher(
            this LoggerEnrichmentConfiguration enrich)
        {
            if (enrich == null)
                throw new ArgumentNullException(nameof(enrich));

            return enrich.With<ExceptionEnricherTest>();
        }
    }

Appsettings in this case :

"Enrich": [ "FromLogContext", "WithCorrelationId", "WithExceptionEnricher" ]

"WriteTo": [
      {
        "Name": "Console",
        "Args": {
          "outputTemplate": "[{Timestamp:yyyy:MM:dd hh:mm:ss} {CorrelationId} {ClientIp} {Level:u3}] {Message:lj}{NewLine}{ExceptionWithoutStackTrace}"
        }
      }]

But I don`t see my custom property.

0

There are 0 best solutions below