Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Exceptions with properties that throw an exception when fetched fail to log #106

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
root=true

[*.config]
indent_style=space
indent_size=2

[*.cs]
indent_style=space
indent_size=4
trim_trailing_whitespace=true
54 changes: 53 additions & 1 deletion src/NLog.Targets.ElasticSearch.Tests/IntegrationTests.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,64 @@
using System;
using NLog.Common;
using NLog.Config;
using NLog.Layouts;
using Xunit;
using Xunit.Abstractions;

namespace NLog.Targets.ElasticSearch.Tests
{
public class IntegrationTests
{
[Fact(Skip ="Integration")]
private readonly ITestOutputHelper testOutputHelper;

public IntegrationTests(ITestOutputHelper testOutputHelper)
{
this.testOutputHelper = testOutputHelper;
}

private class ExceptionWithPropertiesThatThrow : Exception
{
public object ThisPropertyThrowsOnGet => throw new ObjectDisposedException("DisposedObject");
}

[Theory(Skip = "Integration")]
[InlineData(true)]
[InlineData(false)]
public void ExceptionSerializationTest(bool hasExceptionFieldLayout)
{
using (var testOutputTextWriter = new TestOutputTextWriter(testOutputHelper))
{
InternalLogger.LogWriter = testOutputTextWriter;
InternalLogger.LogLevel = LogLevel.Warn;

var elasticTarget = new ElasticSearchTarget();

if (hasExceptionFieldLayout)
{
elasticTarget.Fields.Add(new Field
{
Name = "exception",
Layout = Layout.FromString("${exception:format=toString,Data:maxInnerExceptionLevel=10}"),
LayoutType = typeof(string)
});
}

var rule = new LoggingRule("*", LogLevel.Info, elasticTarget);

var config = new LoggingConfiguration();
config.LoggingRules.Add(rule);

LogManager.Configuration = config;

var logger = LogManager.GetLogger("Example");

logger.Error(new ExceptionWithPropertiesThatThrow(), "Boom");

LogManager.Flush();
}
}

[Fact(Skip = "Integration")]
public void SimpleLogTest()
{
var elasticTarget = new ElasticSearchTarget();
Expand Down
48 changes: 48 additions & 0 deletions src/NLog.Targets.ElasticSearch.Tests/TestOutputTextWriter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using System.IO;
using System.Text;
using Xunit.Abstractions;

namespace NLog.Targets.ElasticSearch.Tests
{
public class TestOutputTextWriter : TextWriter
{
private StringBuilder stringBuilder;
private readonly ITestOutputHelper testOutputHelper;

public TestOutputTextWriter(ITestOutputHelper testOutputHelper)
{
this.stringBuilder = new StringBuilder();
this.testOutputHelper = testOutputHelper;
}

public override Encoding Encoding => Encoding.Unicode;

public override void Write(char value)
{
this.stringBuilder.Append(value);
}

public override void WriteLine(string value)
{
this.stringBuilder.Append(value);

this.Flush();
}

public override void Flush()
{
var sb = this.stringBuilder;
if (sb.Length > 0)
{
this.stringBuilder = new StringBuilder();
this.testOutputHelper.WriteLine(sb.ToString());
}
}

protected override void Dispose(bool disposing)
{
this.Flush();
base.Dispose(disposing);
}
}
}
19 changes: 12 additions & 7 deletions src/NLog.Targets.ElasticSearch/ElasticSearchTarget.cs
Original file line number Diff line number Diff line change
Expand Up @@ -220,13 +220,6 @@ private PostData FormPayload(ICollection<AsyncLogEventInfo> logEvents)
{"message", RenderLogEvent(Layout, logEvent)}
};

if (logEvent.Exception != null)
{
var jsonString = JsonConvert.SerializeObject(logEvent.Exception, _jsonSerializerSettings.Value);
var ex = JsonConvert.DeserializeObject<ExpandoObject>(jsonString);
document.Add("exception", ex.ReplaceDotInKeys());
}

foreach (var field in Fields)
{
var renderedField = RenderLogEvent(field.Layout, logEvent);
Expand All @@ -245,6 +238,13 @@ private PostData FormPayload(ICollection<AsyncLogEventInfo> logEvents)
}
}

if (logEvent.Exception != null && !document.ContainsKey("exception"))
{
var jsonString = JsonConvert.SerializeObject(logEvent.Exception, _jsonSerializerSettings.Value);
var ex = JsonConvert.DeserializeObject<ExpandoObject>(jsonString);
document.Add("exception", ex.ReplaceDotInKeys());
}

if (IncludeAllProperties && logEvent.HasProperties)
{
foreach (var p in logEvent.Properties)
Expand Down Expand Up @@ -282,6 +282,11 @@ private static JsonSerializerSettings CreateJsonSerializerSettings()
{
var jsonSerializerSettings = new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore, CheckAdditionalContent = true };
jsonSerializerSettings.Converters.Add(new StringEnumConverter());
jsonSerializerSettings.Error = (sender, args) =>
{
InternalLogger.Warn(args.ErrorContext.Error, $"Error serializing exception property '{args.ErrorContext.Member}', property ignored");
args.ErrorContext.Handled = true;
};
return jsonSerializerSettings;
}
}
Expand Down