|
| 1 | +// --------------------------------------------------------------------------------------------------------------------- |
| 2 | +// Imports |
| 3 | +// --------------------------------------------------------------------------------------------------------------------- |
| 4 | +using Serilog.Core; |
| 5 | +using Serilog.Events; |
| 6 | + |
| 7 | +namespace CodeOfChaos.Extensions.Serilog.Enrichers; |
| 8 | +// --------------------------------------------------------------------------------------------------------------------- |
| 9 | +// Code |
| 10 | +// --------------------------------------------------------------------------------------------------------------------- |
| 11 | +public class TruncateSourceContextEnricher : ILogEventEnricher { |
| 12 | + public int MaxLength { get; } = 8; |
| 13 | + |
| 14 | + // ----------------------------------------------------------------------------------------------------------------- |
| 15 | + // Constructors |
| 16 | + // ----------------------------------------------------------------------------------------------------------------- |
| 17 | + public TruncateSourceContextEnricher() { } |
| 18 | + public TruncateSourceContextEnricher(int maxLength) => MaxLength = maxLength; |
| 19 | + |
| 20 | + // ----------------------------------------------------------------------------------------------------------------- |
| 21 | + // Methods |
| 22 | + // ----------------------------------------------------------------------------------------------------------------- |
| 23 | + public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory) { |
| 24 | + if (!logEvent.Properties.TryGetValue("SourceContext", out LogEventPropertyValue? sourceContextValue) |
| 25 | + || sourceContextValue is not ScalarValue { Value: string sourceContext }) return; |
| 26 | + |
| 27 | + string truncatedSourceContext = sourceContext.Length > MaxLength + 3 |
| 28 | + ? string.Concat("...", sourceContext.AsSpan(sourceContext.Length - MaxLength, MaxLength)) |
| 29 | + : sourceContext; |
| 30 | + |
| 31 | + var truncatedProperty = new LogEventProperty("SourceContext", new ScalarValue(truncatedSourceContext)); |
| 32 | + logEvent.AddOrUpdateProperty(truncatedProperty); |
| 33 | + } |
| 34 | +} |
0 commit comments