Skip to content

Commit 09b9ec3

Browse files
committed
MessageLayoutRenderer - Handle Exception ToString can throw with AOT
1 parent 198075a commit 09b9ec3

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

src/NLog/LayoutRenderers/ExceptionLayoutRenderer.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -440,8 +440,8 @@ protected virtual void AppendToString(StringBuilder sb, Exception ex)
440440

441441
try
442442
{
443-
exceptionMessage = ex.Message;
444443
innerException = ex.InnerException;
444+
exceptionMessage = ex.Message;
445445
sb.Append(ex.ToString());
446446
}
447447
catch (Exception exception)

src/NLog/LayoutRenderers/MessageLayoutRenderer.cs

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ namespace NLog.LayoutRenderers
3535
{
3636
using System;
3737
using System.Text;
38+
using NLog.Common;
3839
using NLog.Config;
3940
using NLog.Internal;
4041

@@ -96,7 +97,31 @@ protected override void Append(StringBuilder builder, LogEventInfo logEvent)
9697
Exception primaryException = GetPrimaryException(logEvent.Exception);
9798
if (!exceptionOnly)
9899
builder.Append(ExceptionSeparator);
99-
builder.Append(primaryException.ToString());
100+
101+
AppendExceptionToString(builder, primaryException);
102+
}
103+
}
104+
105+
private static void AppendExceptionToString(StringBuilder builder, Exception exception)
106+
{
107+
string exceptionMessage = string.Empty;
108+
Exception? innerException = null;
109+
110+
try
111+
{
112+
innerException = exception.InnerException;
113+
exceptionMessage = exception.Message;
114+
builder.Append(exception.ToString());
115+
}
116+
catch (Exception ex)
117+
{
118+
InternalLogger.Warn(ex, "Message-LayoutRenderer Could not output ToString for Exception: {0}", exception.GetType());
119+
builder.Append($"{exception.GetType()}: {exceptionMessage}");
120+
if (innerException != null)
121+
{
122+
builder.AppendLine();
123+
AppendExceptionToString(builder, innerException);
124+
}
100125
}
101126
}
102127

0 commit comments

Comments
 (0)