Skip to content

Exception in StackTrace leads to wrong message being logged #2165

@Falco20019

Description

@Falco20019

Description
If something goes wrong during ToString() on an exception, the root cause is not logged anymore.

Reproduction

  1. Create a dummy exception that throws anything in get_StackTrace
  2. Emit a log entry with this exception to RestrictedSink

Expected behavior
The original message of this exception should still be logged with the thrown exception on top. Right now, only the thrown exception is logged and the original exception causing the issue is lost.

Relevant package, tooling and runtime versions
Serilog 4.2.0
Serilog.Sinks.File 6.0.0

Additional context
We got the following exception:

2025-03-20T10:27:02.4043236Z Caught exception while emitting to sink Serilog.Core.Sinks.RestrictedSink: System.TypeLoadException: Could not resolve type 'Company.Core.DataPersistence.Db.DbDataPersistor' in assembly 'Company.Core.DataPersistence, Version=2.1.1.0, Culture=neutral, PublicKeyToken=null'.
   at System.Reflection.TypeNameParser.GetTypeFromDefaultAssemblies(String typeName, ReadOnlySpan`1 nestedTypeNames)
   at System.Reflection.TypeNameParser.GetType(String typeName, ReadOnlySpan`1 nestedTypeNames, String assemblyNameIfAny)
   at System.Reflection.TypeNameParser.NestedNamespaceTypeName.ResolveType(TypeNameParser& parser, String containingAssemblyIfAny)
   at System.Reflection.TypeNameParser.Parse()
   at System.Reflection.TypeNameParser.GetTypeHelper(Char* pTypeName, RuntimeAssembly requestingAssembly, Boolean throwOnError, Boolean requireAssemblyQualifiedName)
   at System.Reflection.CustomAttribute._CreateCaObject(RuntimeModule pModule, RuntimeType type, IRuntimeMethodInfo pCtor, Byte** ppBlob, Byte* pEndBlob, Int32* pcNamedArgs)
   at System.Reflection.CustomAttribute.AddCustomAttributes(ListBuilder`1& attributes, RuntimeModule decoratedModule, Int32 decoratedMetadataToken, RuntimeType attributeFilterType, Boolean mustBeInheritable, ListBuilder`1 derivedAttributes)   at System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeModule decoratedModule, Int32 decoratedMetadataToken, Int32 pcaCount, RuntimeType attributeFilterType)
   at System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeMethodInfo method, RuntimeType caType, Boolean inherit)
   at System.Attribute.GetCustomAttributes(MemberInfo element, Type attributeType, Boolean inherit)
   at System.Diagnostics.StackTrace.TryResolveStateMachineMethod(MethodBase& method, Type& declaringType)
   at System.Diagnostics.StackTrace.ToString(TraceFormat traceFormat, StringBuilder sb)
   at System.Diagnostics.StackTrace.ToString(TraceFormat traceFormat)
   at System.Exception.get_StackTrace()
   at System.IO.FileNotFoundException.ToString()
   at Serilog.Templates.Themes.ThemedJsonValueFormatter.FormatLiteralValue(ScalarValue scalar, TextWriter output)
   at Serilog.Templates.Themes.ThemedJsonValueFormatter.VisitScalarValue(TextWriter state, ScalarValue scalar)
   at Serilog.Data.LogEventPropertyValueVisitor`2.Visit(TState state, LogEventPropertyValue value)
   at Serilog.Templates.Themes.ThemedJsonValueFormatter.VisitStructureValue(TextWriter state, StructureValue structure)
   at Serilog.Data.LogEventPropertyValueVisitor`2.Visit(TState state, LogEventPropertyValue value)
   at Serilog.Templates.Themes.ThemedJsonValueFormatter.Format(LogEventPropertyValue value, TextWriter output)
   at Serilog.Templates.Compilation.CompiledFormattedExpression.EvaluateUnaligned(EvaluationContext ctx, TextWriter output, IFormatProvider formatProvider, Int32& invisibleCharacterCount)
   at Serilog.Templates.Compilation.CompiledFormattedExpression.Evaluate(EvaluationContext ctx, TextWriter output)
   at Serilog.Templates.Compilation.CompiledTemplateBlock.Evaluate(EvaluationContext ctx, TextWriter output)
   at Serilog.Templates.ExpressionTemplate.Format(LogEvent logEvent, TextWriter output)
   at Serilog.Sinks.File.FileSink.Serilog.Sinks.File.IFileSink.EmitOrOverflow(LogEvent logEvent) in K:\GitRepos\serilog-sinks-file\src\Serilog.Sinks.File\Sinks\File\FileSink.cs:line 120
   at Serilog.Sinks.File.RollingFileSink.Emit(LogEvent logEvent) in K:\GitRepos\serilog-sinks-file\src\Serilog.Sinks.File\Sinks\File\RollingFileSink.cs:line 85
   at Serilog.Sinks.File.PeriodicFlushToDiskSink.Emit(LogEvent logEvent) in K:\GitRepos\serilog-sinks-file\src\Serilog.Sinks.File\Sinks\File\PeriodicFlushToDiskSink.cs:line 56
   at Serilog.Core.Sinks.RestrictedSink.Emit(LogEvent logEvent)
   at Serilog.Core.Sinks.SafeAggregateSink.Emit(LogEvent logEvent)

The real exception was Could not load file or assembly 'Microsoft.EntityFrameworkCore, Version=8.0.14.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. Das System kann die angegebene Datei nicht finden. because we had 8.0.11 in the package. The real StackTrace was as follows:

   at Company.Core.DataPersistence.Db.DbDataPersistor.<RetrieveAsync>d__6.MoveNext()
   at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine)
   at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Start[TStateMachine](TStateMachine& stateMachine)
   at Company.Core.DataPersistence.Db.DbDataPersistor.RetrieveAsync(Uuid uuid, String namespace, CancellationToken cancellationToken)
   at Company.Component.MrPeripheralControl.Helpers.PersistDataHelper.<GetPersistenceDataAsync>d__8.MoveNext()
   at Company.Component.MrPeripheralControl.Handlers.MrPeripheralControlHandler.<StartingAsync>d__10.MoveNext()

But SerializationStackTraceString fails since it tries to use some Reflection on the type which is not possible due to the TypeLoadException, going full circle...

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions