Skip to content

Commit 100a4b9

Browse files
authored
Merge pull request #310 from KodrAus/feat/trace-sample
Add tracing to seqcli sample ingest
2 parents cb6b984 + 75718d4 commit 100a4b9

File tree

7 files changed

+44
-21
lines changed

7 files changed

+44
-21
lines changed

src/Roastery/Data/Database.cs

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@
77
using System.Threading.Tasks;
88
using Roastery.Util;
99
using Serilog;
10+
using Serilog.Events;
11+
using SerilogTracing;
12+
using SerilogTracing.Instrumentation;
1013

1114
namespace Roastery.Data;
1215

@@ -134,17 +137,23 @@ static string AsSqlLiteral(object? o)
134137

135138
async Task LogExecAsync(string sql, int rowCount)
136139
{
140+
using var activity = _logger.StartActivity("Execution of {Sql}", sql);
141+
137142
if (Distribution.OnceIn(200))
138143
{
139-
throw new OperationCanceledException(
144+
var exception = new OperationCanceledException(
140145
"A deadlock was detected and the transaction chosen as the deadlock victim.");
141-
}
142146

143-
var sw = Stopwatch.StartNew();
147+
activity.Complete(LogEventLevel.Error, exception);
148+
149+
throw exception;
150+
}
151+
152+
144153
var delay = 10 + (int)(Distribution.Uniform() * Math.Pow(rowCount, 1.6));
145154
await Task.Delay(delay);
146-
_logger.Debug("Execution of {Sql} affected {RowCount} rows in {Elapsed:0.000} ms",
147-
sql, rowCount, sw.Elapsed.TotalMilliseconds);
155+
156+
activity.AddProperty("RowCount", rowCount);
148157
}
149158

150159
static T Clone<T>(T value) where T: IIdentifiable, new()

src/Roastery/Program.cs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ public static async Task Main(ILogger logger, CancellationToken cancellationToke
2121

2222
var database = new Database(webApplicationLogger, "roastery");
2323
DatabaseMigrator.Populate(database);
24-
24+
2525
var client = new HttpClient(
2626
"https://roastery.datalust.co",
2727
new NetworkLatencyMiddleware(
@@ -35,13 +35,13 @@ public static async Task Main(ILogger logger, CancellationToken cancellationToke
3535
}, webApplicationLogger))))));
3636

3737
var agents = new List<Agent>();
38-
38+
3939
for (var i = 0; i < 100; ++i)
4040
agents.Add(new Customer(client, Person.Generate(), (int)Distribution.Uniform(60000, 180000)));
41-
41+
4242
for (var i = 0; i < 3; ++i)
4343
agents.Add(new WarehouseStaff(client));
44-
44+
4545
var batchApplicationLogger = logger.ForContext("Application", "Roastery Batch Processing");
4646
agents.Add(new CatalogBatch(client, batchApplicationLogger));
4747
agents.Add(new ArchivingBatch(client, batchApplicationLogger));

src/Roastery/Roastery.csproj

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,10 @@
44
<TargetFramework>net8.0</TargetFramework>
55
<Nullable>enable</Nullable>
66
</PropertyGroup>
7-
7+
88
<ItemGroup>
99
<PackageReference Include="Serilog" Version="3.1.1" />
10+
<PackageReference Include="SerilogTracing" Version="1.0.0-dev-00088" />
1011
</ItemGroup>
1112

1213
</Project>

src/Roastery/Web/RequestLoggingMiddleware.cs

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
using System;
2-
using System.Diagnostics;
32
using System.Net;
43
using System.Threading.Tasks;
54
using Serilog;
65
using Serilog.Context;
76
using Serilog.Events;
7+
using SerilogTracing;
8+
using SerilogTracing.Instrumentation;
89

910
namespace Roastery.Web;
1011

@@ -22,15 +23,16 @@ public RequestLoggingMiddleware(ILogger logger, HttpServer next)
2223
public override async Task<HttpResponse> InvokeAsync(HttpRequest request)
2324
{
2425
using var _ = LogContext.PushProperty("RequestId", request.RequestId);
25-
26-
var sw = Stopwatch.StartNew();
26+
27+
using var activity = _logger.StartActivity("HTTP {RequestMethod} {RequestPath}", request.Method, request.Path);
28+
2729
try
2830
{
2931
var response = await _next.InvokeAsync(request);
30-
LogCompletion(null, request, sw, response.StatusCode);
32+
LogCompletion(activity, null, response.StatusCode);
3133
return response;
3234
}
33-
catch (Exception ex1) when (LogCompletion(ex1, request, sw, HttpStatusCode.InternalServerError))
35+
catch (Exception ex1) when (LogCompletion(activity, ex1, HttpStatusCode.InternalServerError))
3436
{
3537
// We never hit this, because the exception filter always returns false.
3638
throw;
@@ -41,12 +43,13 @@ public override async Task<HttpResponse> InvokeAsync(HttpRequest request)
4143
}
4244
}
4345

44-
bool LogCompletion(Exception? exception, HttpRequest request, Stopwatch sw, HttpStatusCode statusCode)
46+
bool LogCompletion(LoggerActivity activity, Exception? exception, HttpStatusCode statusCode)
4547
{
4648
var level = (int)statusCode >= 500 ? LogEventLevel.Error : LogEventLevel.Information;
47-
_logger.Write(level, exception,
48-
"HTTP {RequestMethod} {RequestPath} responded {StatusCode} in {Elapsed:0.000} ms",
49-
request.Method, request.Path, (int)statusCode, sw.Elapsed.TotalMilliseconds);
49+
50+
activity.AddProperty("StatusCode", (int)statusCode);
51+
activity.Complete(level, exception);
52+
5053
return false;
5154
}
5255
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
namespace SeqCli.Ingestion;
2+
3+
static class TraceConstants
4+
{
5+
internal const string ParentSpanIdProperty = "ParentSpanId";
6+
7+
internal const string SpanStartTimestampProperty = "SpanStartTimestamp";
8+
}

src/SeqCli/Output/OutputFormatter.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
using SeqCli.Ingestion;
12
using SeqCli.Levels;
23
using Serilog.Formatting;
34
using Serilog.Templates;
@@ -7,6 +8,6 @@ namespace SeqCli.Output;
78
static class OutputFormatter
89
{
910
internal static readonly ITextFormatter Json = new ExpressionTemplate(
10-
$"{{ {{@t, @mt, @l: coalesce({LevelMapping.SurrogateLevelProperty}, if @l = 'Information' then undefined() else @l), @x, @sp, @tr, @ps, @st, ..rest()}} }}\n"
11+
$"{{ {{@t, @mt, @l: coalesce({LevelMapping.SurrogateLevelProperty}, if @l = 'Information' then undefined() else @l), @x, @sp, @tr, @ps: coalesce({TraceConstants.ParentSpanIdProperty}, @ps), @st: coalesce({TraceConstants.SpanStartTimestampProperty}, @st), ..rest()}} }}\n"
1112
);
1213
}

src/SeqCli/Sample/Loader/Simulation.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
using Seq.Api;
1818
using SeqCli.Ingestion;
1919
using Serilog;
20+
using SerilogTracing;
2021

2122
namespace SeqCli.Sample.Loader;
2223

@@ -26,7 +27,7 @@ public static async Task RunAsync(SeqConnection connection, string? apiKey, int
2627
{
2728
var buffer = new BufferingSink();
2829

29-
await using var logger = new LoggerConfiguration()
30+
var logger = new LoggerConfiguration()
3031
.MinimumLevel.Debug()
3132
.Enrich.FromLogContext()
3233
.Enrich.WithProperty("Origin", "seqcli sample ingest")

0 commit comments

Comments
 (0)