Skip to content

Commit 6558a73

Browse files
authored
feat(aspire): surface exception detail in routed OTLP logs (#6347) (#6348)
* feat(aspire): surface exception detail in routed OTLP logs (#6347) When an SUT logs an exception, the OTLP body is usually just the message template; the failure detail lives in the exception.* semantic-convention attributes the OTLP log exporter attaches (OpenTelemetry .NET 1.8.0+). OtlpLogParser now reads LogRecord.attributes (field 6) and extracts exception.type / exception.message / exception.stacktrace. ProcessLogs prints the exception block after the body line, so a failing test shows why it failed. Prefers the full stack trace; falls back to "type: message". * refactor(aspire): simplify OTLP exception surfacing after review - Drop OtlpLogRecord.HasException — derivable from FormatException(); ProcessLogs now calls FormatException() once instead of walking the fields twice. - Guard the field-6 attribute parse (ParseExceptionAttribute) so only exception.* values are materialised — avoids allocating discarded value strings for the many non-exception attributes a record can carry on the ingest hot path. - Print the exception line with the same [severity] prefix as the body line. - Consolidate the test builder: BuildLogsExportRequest gains optional severity + exception params, replacing the near-duplicate BuildLogsExportRequestWithException. * fix(aspire): add default clause to exception-attr switch (Codacy S131)
1 parent 7bb643c commit 6558a73

3 files changed

Lines changed: 201 additions & 5 deletions

File tree

‎TUnit.OpenTelemetry.Tests/OtlpReceiverIngestionTests.cs‎

Lines changed: 86 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -312,7 +312,87 @@ public async Task Receiver_LogWithServiceName_RecordsSeenService()
312312
await Assert.That(receiver.Diagnostics.LogsRecordsParsed).IsEqualTo(1);
313313
}
314314

315-
private static byte[] BuildLogsExportRequest(string serviceName, string traceId, string body)
315+
[Test]
316+
public async Task Parser_LogWithExceptionAttributes_ExtractsAndFormatsException()
317+
{
318+
var traceId = Guid.NewGuid().ToString("N");
319+
const string stackTrace = "System.InvalidOperationException: boom\n at Sut.Fail()";
320+
var body = BuildLogsExportRequest(
321+
"my-service",
322+
traceId,
323+
"Could not say hello",
324+
severityText: "ERROR",
325+
exceptionType: "System.InvalidOperationException",
326+
exceptionMessage: "boom",
327+
exceptionStackTrace: stackTrace);
328+
329+
var records = OtlpLogParser.Parse(body);
330+
331+
await Assert.That(records.Count).IsEqualTo(1);
332+
var record = records[0];
333+
await Assert.That(record.Body).IsEqualTo("Could not say hello");
334+
await Assert.That(record.ExceptionType).IsEqualTo("System.InvalidOperationException");
335+
await Assert.That(record.ExceptionMessage).IsEqualTo("boom");
336+
await Assert.That(record.ExceptionStackTrace).IsEqualTo(stackTrace);
337+
// Full stack trace preferred over the discrete type/message fields.
338+
await Assert.That(record.FormatException()).IsEqualTo(stackTrace);
339+
}
340+
341+
[Test]
342+
public async Task Parser_LogWithoutException_HasNoExceptionDetail()
343+
{
344+
var traceId = Guid.NewGuid().ToString("N");
345+
var body = BuildLogsExportRequest("my-service", traceId, "just a log line");
346+
347+
var records = OtlpLogParser.Parse(body);
348+
349+
await Assert.That(records.Count).IsEqualTo(1);
350+
var record = records[0];
351+
await Assert.That(record.FormatException()).IsNull();
352+
}
353+
354+
[Test]
355+
public async Task Parser_ExceptionTypeAndMessageOnly_FormatsAsTypeColonMessage()
356+
{
357+
var traceId = Guid.NewGuid().ToString("N");
358+
var body = BuildLogsExportRequest(
359+
"my-service",
360+
traceId,
361+
"boom happened",
362+
severityText: "ERROR",
363+
exceptionType: "System.InvalidOperationException",
364+
exceptionMessage: "boom");
365+
366+
var records = OtlpLogParser.Parse(body);
367+
368+
await Assert.That(records.Count).IsEqualTo(1);
369+
var record = records[0];
370+
// No stack trace available → fall back to "type: message".
371+
await Assert.That(record.FormatException()).IsEqualTo("System.InvalidOperationException: boom");
372+
}
373+
374+
private static void WriteExceptionAttribute(MemoryStream logRecordStream, string key, string value)
375+
{
376+
if (string.IsNullOrEmpty(value))
377+
{
378+
return;
379+
}
380+
381+
// KeyValue { key (1), value = AnyValue (2) } written to LogRecord.attributes (field 6).
382+
using var kvStream = new MemoryStream();
383+
WriteStringField(kvStream, 1, key);
384+
WriteField(kvStream, 2, BuildAnyValue(value));
385+
WriteField(logRecordStream, 6, kvStream.ToArray());
386+
}
387+
388+
private static byte[] BuildLogsExportRequest(
389+
string serviceName,
390+
string traceId,
391+
string body,
392+
string severityText = "INFO",
393+
string exceptionType = "",
394+
string exceptionMessage = "",
395+
string exceptionStackTrace = "")
316396
{
317397
// KeyValue { key = "service.name", value = AnyValue(serviceName) }
318398
using var kvStream = new MemoryStream();
@@ -323,10 +403,13 @@ private static byte[] BuildLogsExportRequest(string serviceName, string traceId,
323403
using var resourceStream = new MemoryStream();
324404
WriteField(resourceStream, 1, kvStream.ToArray());
325405

326-
// LogRecord { severity_text (3), body (5), trace_id (9) }
406+
// LogRecord { severity_text (3), body (5), attributes (6)*, trace_id (9) }
327407
using var logRecordStream = new MemoryStream();
328-
WriteStringField(logRecordStream, 3, "INFO");
408+
WriteStringField(logRecordStream, 3, severityText);
329409
WriteField(logRecordStream, 5, BuildAnyValue(body));
410+
WriteExceptionAttribute(logRecordStream, "exception.type", exceptionType);
411+
WriteExceptionAttribute(logRecordStream, "exception.message", exceptionMessage);
412+
WriteExceptionAttribute(logRecordStream, "exception.stacktrace", exceptionStackTrace);
330413
WriteField(logRecordStream, 9, Convert.FromHexString(traceId));
331414

332415
// ScopeLogs { log_records (field 2) = [logRecord] }

‎TUnit.OpenTelemetry/Receiver/OtlpLogParser.cs‎

Lines changed: 105 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,12 +13,51 @@ namespace TUnit.OpenTelemetry.Receiver;
1313
/// other value types (int, bool, kvlist, array) are not currently extracted.
1414
/// </param>
1515
/// <param name="ResourceName">The <c>service.name</c> resource attribute, if present.</param>
16+
/// <param name="ExceptionType">
17+
/// The <c>exception.type</c> log attribute, if present. Populated by the OTLP log exporter
18+
/// (OpenTelemetry .NET 1.8.0+) whenever a log record carries an exception. Empty otherwise.
19+
/// </param>
20+
/// <param name="ExceptionMessage">The <c>exception.message</c> log attribute, if present. Empty otherwise.</param>
21+
/// <param name="ExceptionStackTrace">
22+
/// The <c>exception.stacktrace</c> log attribute, if present. In OpenTelemetry .NET this is the
23+
/// full <c>Exception.ToString()</c> (type, message, and stack), so it already subsumes the type
24+
/// and message fields. Empty otherwise.
25+
/// </param>
1626
internal readonly record struct OtlpLogRecord(
1727
string TraceId,
1828
string SeverityText,
1929
int SeverityNumber,
2030
string Body,
21-
string ResourceName);
31+
string ResourceName,
32+
string ExceptionType = "",
33+
string ExceptionMessage = "",
34+
string ExceptionStackTrace = "")
35+
{
36+
/// <summary>
37+
/// Renders the exception attributes into a single human-readable block, or <c>null</c> when the
38+
/// record carries no exception. Prefers <see cref="ExceptionStackTrace"/> (the full
39+
/// <c>ToString()</c>); otherwise falls back to <c>type: message</c> from the discrete fields.
40+
/// </summary>
41+
public string? FormatException()
42+
{
43+
if (!string.IsNullOrEmpty(ExceptionStackTrace))
44+
{
45+
return ExceptionStackTrace;
46+
}
47+
48+
if (!string.IsNullOrEmpty(ExceptionType) && !string.IsNullOrEmpty(ExceptionMessage))
49+
{
50+
return $"{ExceptionType}: {ExceptionMessage}";
51+
}
52+
53+
if (!string.IsNullOrEmpty(ExceptionType))
54+
{
55+
return ExceptionType;
56+
}
57+
58+
return string.IsNullOrEmpty(ExceptionMessage) ? null : ExceptionMessage;
59+
}
60+
}
2261

2362
/// <summary>
2463
/// Minimal parser for OTLP ExportLogsServiceRequest protobuf messages.
@@ -154,6 +193,9 @@ private static bool ParseScopeLogs(ProtobufReader reader, string resourceName, L
154193
var severityNumber = 0;
155194
var severityText = "";
156195
var body = "";
196+
var exceptionType = "";
197+
var exceptionMessage = "";
198+
var exceptionStackTrace = "";
157199

158200
while (reader.TryReadTag(out var fieldNumber, out var wireType))
159201
{
@@ -172,6 +214,31 @@ private static bool ParseScopeLogs(ProtobufReader reader, string resourceName, L
172214
body = ParseAnyValueString(bodyMsg);
173215
break;
174216

217+
// LogRecord.attributes (field 6) — OpenTelemetry's OTLP log exporter attaches the
218+
// exception.* semantic-convention attributes here whenever a record carries an
219+
// exception. Pull those three out so the exception can be surfaced alongside the body
220+
// (the body alone is often just the log message, not the failure detail).
221+
case 6 when wireType == WireType.LengthDelimited:
222+
var (key, value) = ParseExceptionAttribute(reader.ReadEmbeddedMessage());
223+
switch (key)
224+
{
225+
case "exception.type":
226+
exceptionType = value;
227+
break;
228+
case "exception.message":
229+
exceptionMessage = value;
230+
break;
231+
case "exception.stacktrace":
232+
exceptionStackTrace = value;
233+
break;
234+
default:
235+
// ParseExceptionAttribute already filters to the three exception.* keys;
236+
// any other attribute arrives with an empty value and is ignored.
237+
break;
238+
}
239+
240+
break;
241+
175242
case 9 when wireType == WireType.LengthDelimited:
176243
var traceBytes = reader.ReadBytesAsSpan();
177244
if (traceBytes.Length == 16)
@@ -192,7 +259,15 @@ private static bool ParseScopeLogs(ProtobufReader reader, string resourceName, L
192259
return null;
193260
}
194261

195-
return new OtlpLogRecord(traceId, severityText, severityNumber, body, resourceName);
262+
return new OtlpLogRecord(
263+
traceId,
264+
severityText,
265+
severityNumber,
266+
body,
267+
resourceName,
268+
exceptionType,
269+
exceptionMessage,
270+
exceptionStackTrace);
196271
}
197272

198273
private static string ParseAnyValueString(ProtobufReader reader)
@@ -211,6 +286,34 @@ private static string ParseAnyValueString(ProtobufReader reader)
211286
return "";
212287
}
213288

289+
// Like ParseKeyValue, but materialises the value string only for the exception.* keys the
290+
// receiver renders. A log record can carry many attributes (scopes, custom fields); parsing
291+
// every value — some large — just to discard it would waste allocations on the ingest hot
292+
// path. Assumes key (field 1) precedes value (field 2), which holds for all known OTel encoders.
293+
private static (string Key, string Value) ParseExceptionAttribute(ProtobufReader reader)
294+
{
295+
var key = "";
296+
297+
while (reader.TryReadTag(out var fieldNumber, out var wireType))
298+
{
299+
if (fieldNumber == 1 && wireType == WireType.LengthDelimited)
300+
{
301+
key = reader.ReadString();
302+
}
303+
else if (fieldNumber == 2 && wireType == WireType.LengthDelimited
304+
&& key is "exception.type" or "exception.message" or "exception.stacktrace")
305+
{
306+
return (key, ParseAnyValueString(reader.ReadEmbeddedMessage()));
307+
}
308+
else
309+
{
310+
reader.Skip(wireType);
311+
}
312+
}
313+
314+
return (key, "");
315+
}
316+
214317
private static (string Key, string Value) ParseKeyValue(ProtobufReader reader)
215318
{
216319
var key = "";

‎TUnit.OpenTelemetry/Receiver/OtlpReceiver.cs‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -602,6 +602,16 @@ private void ProcessLogs(byte[] body)
602602
: $"[{record.ResourceName}] ";
603603

604604
testContext.Output.WriteLine($"{prefix}[{severity}] {record.Body}");
605+
606+
// When the SUT logged an exception, the OTLP body is usually just the message
607+
// template — the actual stack trace lives in the exception.* attributes. Surface it
608+
// so a failing test shows *why* it failed, not only that an error was logged.
609+
var exceptionDetail = record.FormatException();
610+
if (exceptionDetail is not null)
611+
{
612+
testContext.Output.WriteLine($"{prefix}[{severity}] {exceptionDetail}");
613+
}
614+
605615
Interlocked.Increment(ref _diagnostics.LogsRecordsRouted);
606616
}
607617
}

0 commit comments

Comments
 (0)