Skip to content

Commit

Permalink
Merge branch 'exception-tostring-formatting' into 'master'
Browse files Browse the repository at this point in the history
Use ToString to render exception

See merge request vostok-libraries/logging.formatting!1
  • Loading branch information
Пономарёв Игорь Евгеньевич committed Jan 31, 2024
2 parents fd7c6e9 + ec5cfa9 commit 6c90ab9
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 62 deletions.
28 changes: 8 additions & 20 deletions Vostok.Logging.Formatting.Tests/Tokens/ExceptionToken_Tests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,36 +26,24 @@ public void Should_not_render_anything_for_null_exception()
}

[Test]
public void Should_correctly_format_type_and_messages_for_exceptions_without_nested_exceptions()
public void Should_use_ToString_to_render_exception()
{
try
{
throw new Exception("error1");
throw new Exception("error1", new Exception("error2"));
}
catch (Exception error)
{
var result = Format(error);

Console.Out.WriteLine(result);

result.Should().StartWith("System.Exception: error1");
}
}

[Test]
public void Should_correctly_format_type_and_messages_for_exceptions_with_nested_exceptions()
{
try
{
throw new Exception("error1", new Exception("error2", new FormatException("error3")));
}
catch (Exception error)
{
var result = Format(error);

Console.Out.WriteLine(result);

result.Should().StartWith("System.Exception: error1 ---> System.Exception: error2 ---> System.FormatException: error3");
result.Should()
.Contain(error.ToString())
.And.Contain(typeof(Exception).FullName)
.And.Contain("error1")
.And.Contain("error2")
.And.Contain(nameof(Should_use_ToString_to_render_exception));
}
}

Expand Down
43 changes: 1 addition & 42 deletions Vostok.Logging.Formatting/Tokens/ExceptionToken.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,48 +19,7 @@ public override void Render(LogEvent @event, TextWriter writer, IFormatProvider
if (@event.Exception == null)
return;

RenderException(@event.Exception, writer, 0);
writer.WriteLine();
}

private static void RenderException(Exception error, TextWriter writer, int depth)
{
if (error == null)
return;

if (depth > MaximumDepth)
{
writer.Write("<too deep>");
return;
}

writer.Write(error.GetType().ToString());

var errorMessage = error.Message;
if (errorMessage != null)
{
writer.Write(": ");
writer.Write(errorMessage);
}

var innerError = error.InnerException;
if (innerError != null)
{
writer.Write(" ---> ");

RenderException(innerError, writer, depth + 1);

writer.WriteLine();
writer.Write(" ");
writer.Write("--- End of inner exception stack trace ---");
}

var stackTrace = error.StackTrace;
if (stackTrace != null)
{
writer.WriteLine();
writer.Write(stackTrace);
}
writer.WriteLine(@event.Exception.ToString());
}
}
}

0 comments on commit 6c90ab9

Please sign in to comment.