Skip to content

Commit

Permalink
Add trace context to LogEntry (#87)
Browse files Browse the repository at this point in the history
* upgrade Serilog from 2.12.0 to 3.1.1

* add TraceId and SpanId to LogEntry

add tests to validate that trace data is saving
  • Loading branch information
fernandovmp authored Sep 7, 2024
1 parent bfa4614 commit d6a5703
Show file tree
Hide file tree
Showing 3 changed files with 116 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/Serilog.Sinks.MongoDB/Serilog.Sinks.MongoDB.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="Serilog" Version="2.12.0" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Formatting.Compact" Version="1.1.0" />
<PackageReference Include="Serilog.Sinks.PeriodicBatching" Version="3.1.0" />
<PackageReference Include="MongoDB.Driver" Version="2.28.0" />
Expand Down
7 changes: 7 additions & 0 deletions src/Serilog.Sinks.MongoDB/Sinks/MongoDB/LogEntry.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
// limitations under the License.

using System;
using System.Diagnostics;
using System.Linq;

using MongoDB.Bson;
Expand Down Expand Up @@ -41,6 +42,10 @@ public class LogEntry
public BsonDocument? Properties { get; set; }

public BsonDocument? Exception { get; set; }
[BsonIgnoreIfNull]
public string? TraceId { get; set; }
[BsonIgnoreIfNull]
public string? SpanId { get; set; }

public static LogEntry MapFrom(LogEvent logEvent, bool includeMessageTemplate)
{
Expand All @@ -51,6 +56,8 @@ public static LogEntry MapFrom(LogEvent logEvent, bool includeMessageTemplate)
RenderedMessage = logEvent.RenderMessage(),
Level = logEvent.Level,
UtcTimeStamp = logEvent.Timestamp.ToUniversalTime().UtcDateTime,
TraceId = logEvent.TraceId?.ToString(),
SpanId = logEvent.SpanId?.ToString(),
Exception = logEvent.Exception?.ToBsonDocument().SanitizeDocumentRecursive(),
Properties = BsonDocument.Create(
logEvent.Properties.ToDictionary(
Expand Down
108 changes: 108 additions & 0 deletions test/Serilog.Sinks.MongoDB.Tests/LoggerWithTraceIdTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
using FluentAssertions;

using Microsoft.Extensions.Configuration;

using MongoDB.Driver;

using Serilog.Helpers;

namespace Serilog.Sinks.MongoDB.Tests;

using System.Diagnostics;
using NUnit.Framework;

[TestFixture]
public class LoggerWithTraceIdTests
{
private const string MongoConnectionString = "mongodb://localhost:27017";

private const string MongoDatabaseName = "mongodb-sink";

private static (MongoClient, IMongoDatabase) GetDatabase()
{
var mongoClient = new MongoClient(MongoConnectionString);
return (mongoClient, mongoClient.GetDatabase(MongoDatabaseName));
}

[Test]
public void Log_Without_Activity_Should_Have_TraceId_And_SpanId_Null()
{
var configuration = new ConfigurationBuilder()
.AddJsonFile("serilog.json")
.Build();

var collectionName = RollingInterval.Month.GetCollectionName("test");

const string Message = "some message logged into mongodb without activity";

using (var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger())
{
logger.Information(Message);
}

var (mongoClient, mongoDatabase) = GetDatabase();
var collectionExists = mongoDatabase.CollectionExists(collectionName);

collectionExists.Should().BeTrue();

var mongoCollection = mongoDatabase.GetCollection<LogEntry>(collectionName);
var document = mongoCollection.Find(x => x.RenderedMessage == Message).FirstOrDefault();

document.Should().NotBeNull();
document.TraceId.Should().BeNull();
document.SpanId.Should().BeNull();

mongoClient.DropDatabase(MongoDatabaseName);
}

[Test]
public void Log_Within_Activity_Should_Have_TraceId_And_SpanId_Not_Null()
{
ActivityTraceId traceId;
ActivitySpanId spanId;

var configuration = new ConfigurationBuilder()
.AddJsonFile("serilog.json")
.Build();

var collectionName = RollingInterval.Month.GetCollectionName("test");

const string Message = "some message logged into mongodb within an activity";

using (var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger())
{
var activitySource = new ActivitySource("Serilog.Sinks.MongoDB.Tests");
var activityListener = new ActivityListener
{
ShouldListenTo = s => true,
SampleUsingParentId = (ref ActivityCreationOptions<string> activityOptions) => ActivitySamplingResult.AllData,
Sample = (ref ActivityCreationOptions<ActivityContext> activityOptions) => ActivitySamplingResult.AllData
};
ActivitySource.AddActivityListener(activityListener);
using (var activity = activitySource.StartActivity("LogTest"))
{
traceId = activity.TraceId;
spanId = activity.SpanId;
logger.Information(Message);
}
}

var (mongoClient, mongoDatabase) = GetDatabase();
var collectionExists = mongoDatabase.CollectionExists(collectionName);

collectionExists.Should().BeTrue();

var mongoCollection = mongoDatabase.GetCollection<LogEntry>(collectionName);
var document = mongoCollection.Find(x => x.RenderedMessage == Message).FirstOrDefault();

document.Should().NotBeNull();
document.TraceId.Should().Be(traceId.ToString());
document.SpanId.Should().Be(spanId.ToString());

mongoClient.DropDatabase(MongoDatabaseName);
}
}

0 comments on commit d6a5703

Please sign in to comment.