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

Elastic.CommonSchema.NLog - MetadataDictionary with safe values #222

Merged
merged 4 commits into from
Jan 16, 2023
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
36 changes: 35 additions & 1 deletion src/Elastic.CommonSchema.NLog/EcsLayout.cs
Original file line number Diff line number Diff line change
Expand Up @@ -309,13 +309,31 @@ private MetadataDictionary GetMetadata(LogEventInfo e)

if (IncludeEventProperties && e.HasProperties)
{
global::NLog.MessageTemplates.MessageTemplateParameters templateParameters = null;

foreach (var prop in e.Properties)
{
var propertyName = prop.Key?.ToString();
if (string.IsNullOrEmpty(propertyName) || ExcludeProperties.Contains(propertyName))
continue;

Populate(metadata, propertyName, prop.Value);
var propertyValue = prop.Value;
if (propertyValue is null || propertyValue is IConvertible || propertyValue.GetType().IsValueType)
{
Populate(metadata, propertyName, propertyValue);
}
else
{
templateParameters = templateParameters ?? e.MessageTemplateParameters;
if (AllowSerializePropertyValue(propertyName, templateParameters))
{
Populate(metadata, propertyName, propertyValue);
}
else
{
Populate(metadata, propertyName, propertyValue?.ToString());
}
}
}
}

Expand Down Expand Up @@ -346,6 +364,22 @@ private MetadataDictionary GetMetadata(LogEventInfo e)
: null;
}

private bool AllowSerializePropertyValue(string propertyName, global::NLog.MessageTemplates.MessageTemplateParameters templateParameters)
{
if (templateParameters.Count > 0 && !templateParameters.IsPositional)
{
// System.Text.Json is very fragile, and can only handle safe objects
// Microsoft ASP.NET often uses message-templates for logging unsafe objects
foreach (var messageProperty in templateParameters)
{
if (propertyName == messageProperty.Name)
return messageProperty.CaptureType == global::NLog.MessageTemplates.CaptureType.Serialize;
}
}

return true; // Not from Message-Template, then probably safe
}

private Log GetLog(LogEventInfo logEventInfo)
{
var logOriginMethod = LogOriginCallSiteMethod?.Render(logEventInfo);
Expand Down
46 changes: 46 additions & 0 deletions tests/Elastic.CommonSchema.NLog.Tests/MessageTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,52 @@ public void SeesMessageWithProp() => TestLogger((logger, getLogEvents) =>
y.Should().HaveValue().And.Be(2.2);
});

[Fact]
public void SeesMessageWithSafeProp() => TestLogger((logger, getLogEvents) =>
{
logger.Info("Info {@SafeValue}", new NiceObject() { ValueX = "X", SomeY = 2.2 });

var logEvents = getLogEvents();
logEvents.Should().HaveCount(1);

var ecsEvents = ToEcsEvents(logEvents);

var (_, info) = ecsEvents.First();
info.Message.Should().Be("Info {\"ValueX\":\"X\", \"SomeY\":2.2}");
info.Metadata.Should().ContainKey("SafeValue");

var x = info.Metadata["SafeValue"] as System.Collections.Generic.Dictionary<string, object>;
x.Should().NotBeNull().And.NotBeEmpty();
});

[Fact]
public void SeesMessageWithUnsafeProp() => TestLogger((logger, getLogEvents) =>
{
logger.Info("Info {UnsafeValue}", new NiceObject() { ValueX = "X", SomeY = 2.2 });

var logEvents = getLogEvents();
logEvents.Should().HaveCount(1);

var ecsEvents = ToEcsEvents(logEvents);

var (_, info) = ecsEvents.First();
info.Message.Should().Be("Info X=X");
info.Metadata.Should().BeNull();
info.Labels.Should().NotBeNull();
info.Labels.Should().ContainKey("UnsafeValue");

var x = info.Labels["UnsafeValue"];
x.Should().NotBeNull().And.Be("X=X");
});

public class NiceObject
{
public string ValueX { get; set; }
public double SomeY { get; set; }

public override string ToString() => $"X={ValueX}";
}

[Fact]
public void SeesMessageWithException() => TestLogger((logger, getLogEvents) =>
{
Expand Down