Skip to content

Commit ce3ba36

Browse files
application insight logging
1 parent ce71d54 commit ce3ba36

11 files changed

Lines changed: 381 additions & 36 deletions

File tree

App/backend-api/Microsoft.GS.DPS.Host/API/ChatHost/Chat.cs

Lines changed: 92 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
using Microsoft.GS.DPS.Model.ChatHost;
22
using Microsoft.GS.DPS.API;
3-
43
using Microsoft.AspNetCore.Mvc;
54
using Microsoft.AspNetCore.Http.HttpResults;
65
using System.Text;
76
using System.Text.Json;
7+
using Microsoft.GS.DPSHost.Helpers;
88

99
namespace Microsoft.GS.DPSHost.API
1010
{
@@ -15,16 +15,48 @@ public static void AddAPIs(WebApplication app)
1515
//RegisterAsync the chat API
1616
app.MapPost("/chat", async (ChatRequest request,
1717
ChatRequestValidator validator,
18-
ChatHost chatHost) =>
18+
ChatHost chatHost,
19+
TelemetryHelper telemetryHelper,
20+
ILogger<Chat> logger) =>
1921
{
20-
if(validator.Validate(request).IsValid == false)
22+
try
2123
{
22-
return Results.BadRequest();
23-
}
24+
if (validator.Validate(request).IsValid == false)
25+
{
26+
telemetryHelper.TrackEvent("ChatRequestValidationFailed", new Dictionary<string, string>
27+
{
28+
{ "endpoint", "/chat" }
29+
});
30+
return Results.BadRequest();
31+
}
32+
33+
var result = await chatHost.Chat(request);
34+
35+
// Track successful chat request
36+
telemetryHelper.TrackEvent("ChatRequestSuccess", new Dictionary<string, string>
37+
{
38+
{ "chatSessionId", result.ChatSessionId ?? "unknown" },
39+
{ "documentCount", result.DocumentIds?.Length.ToString() ?? "0" }
40+
});
2441

25-
var result = await chatHost.Chat(request);
26-
return Results.Ok<ChatResponse>(result);
42+
// Set correlation ID for tracing
43+
if (!string.IsNullOrEmpty(result.ChatSessionId))
44+
{
45+
telemetryHelper.SetActivityTag("chatSessionId", result.ChatSessionId);
46+
}
2747

48+
return Results.Ok<ChatResponse>(result);
49+
}
50+
catch (Exception ex)
51+
{
52+
logger.LogError(ex, "Error processing chat request");
53+
telemetryHelper.TrackException(ex, new Dictionary<string, string>
54+
{
55+
{ "endpoint", "/chat" },
56+
{ "errorType", ex.GetType().Name }
57+
});
58+
throw;
59+
}
2860
})
2961
.DisableAntiforgery();
3062

@@ -35,36 +67,68 @@ public static void AddAPIs(WebApplication app)
3567
app.MapPost("/chatAsync", async (HttpContext ctx,
3668
ChatRequest request,
3769
ChatRequestValidator validator,
38-
ChatHost chatHost) =>
70+
ChatHost chatHost,
71+
TelemetryHelper telemetryHelper,
72+
ILogger<Chat> logger) =>
3973
{
40-
if (validator.Validate(request).IsValid == false)
74+
try
4175
{
42-
return Results.BadRequest();
43-
}
76+
if (validator.Validate(request).IsValid == false)
77+
{
78+
telemetryHelper.TrackEvent("ChatAsyncRequestValidationFailed", new Dictionary<string, string>
79+
{
80+
{ "endpoint", "/chatAsync" }
81+
});
82+
return Results.BadRequest();
83+
}
4484

45-
ctx.Response.ContentType = "text/plain";
85+
ctx.Response.ContentType = "text/plain";
4686

47-
//Make a response as a stream
48-
var result = chatHost.ChatAsync(request).Result;
87+
//Make a response as a stream
88+
var result = chatHost.ChatAsync(request).Result;
4989

50-
//Create a dynamic object to store the response
51-
var response = new
52-
{
53-
result.ChatSessionId,
54-
result.DocumentIds,
55-
result.SuggestingQuestions
56-
};
90+
//Create a dynamic object to store the response
91+
var response = new
92+
{
93+
result.ChatSessionId,
94+
result.DocumentIds,
95+
result.SuggestingQuestions
96+
};
97+
98+
//Add the response to the header
99+
ctx.Response.Headers.Add("RESPONSE", JsonSerializer.Serialize(response));
57100

58-
//Add the response to the header
59-
ctx.Response.Headers.Add("RESPONSE", JsonSerializer.Serialize(response));
101+
// Track successful chat async request
102+
telemetryHelper.TrackEvent("ChatAsyncRequestSuccess", new Dictionary<string, string>
103+
{
104+
{ "chatSessionId", result.ChatSessionId ?? "unknown" },
105+
{ "documentCount", result.DocumentIds?.Length.ToString() ?? "0" }
106+
});
60107

61-
// Stream the response
62-
await foreach (var word in result.AnswerWords)
108+
// Set correlation ID for tracing
109+
if (!string.IsNullOrEmpty(result.ChatSessionId))
110+
{
111+
telemetryHelper.SetActivityTag("chatSessionId", result.ChatSessionId);
112+
}
113+
114+
// Stream the response
115+
await foreach (var word in result.AnswerWords)
116+
{
117+
await ctx.Response.WriteAsync(word);
118+
await ctx.Response.WriteAsync(" ");
119+
}
120+
return Results.Ok();
121+
}
122+
catch (Exception ex)
63123
{
64-
await ctx.Response.WriteAsync(word);
65-
await ctx.Response.WriteAsync(" ");
124+
logger.LogError(ex, "Error processing chat async request");
125+
telemetryHelper.TrackException(ex, new Dictionary<string, string>
126+
{
127+
{ "endpoint", "/chatAsync" },
128+
{ "errorType", ex.GetType().Name }
129+
});
130+
throw;
66131
}
67-
return Results.Ok();
68132
})
69133
.DisableAntiforgery();
70134
}

App/backend-api/Microsoft.GS.DPS.Host/API/KernelMemory/KernelMemory.cs

Lines changed: 52 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@
88
using Microsoft.GS.DPS.Model.KernelMemory;
99
using Microsoft.AspNetCore.Http.HttpResults;
1010
using Microsoft.GS.DPS.Storage.Document;
11-
1211
using HeyRed.Mime;
12+
using Microsoft.GS.DPSHost.Helpers;
1313

1414
namespace Microsoft.GS.DPSHost.API
1515
{
@@ -20,7 +20,9 @@ public static void AddAPIs(WebApplication app)
2020
{
2121
//Registration the files
2222
app.MapPost("/Documents/ImportDocument", async (IFormFile file,
23-
DPS.API.KernelMemory kernelMemory
23+
DPS.API.KernelMemory kernelMemory,
24+
TelemetryHelper telemetryHelper,
25+
ILogger<KernelMemory> logger
2426
) =>
2527
{
2628
try
@@ -44,6 +46,11 @@ DPS.API.KernelMemory kernelMemory
4446

4547
if (!allowedExtensions.Contains(fileExtension))
4648
{
49+
telemetryHelper.TrackEvent("DocumentImportUnsupportedFileType", new Dictionary<string, string>
50+
{
51+
{ "fileExtension", fileExtension },
52+
{ "contentType", contentType }
53+
});
4754
return Results.BadRequest(new DocumentImportedResult() { DocumentId = string.Empty,
4855
MimeType = contentType,
4956
Summary = $"{fileExtension} file is Unsupported file type" });
@@ -52,6 +59,10 @@ DPS.API.KernelMemory kernelMemory
5259
// Checking File Size: O byte/kb file not allowed
5360
if (file == null || file.Length == 0)
5461
{
62+
telemetryHelper.TrackEvent("DocumentImportEmptyFile", new Dictionary<string, string>
63+
{
64+
{ "fileName", file?.FileName ?? "unknown" }
65+
});
5566
return Results.BadRequest(new DocumentImportedResult()
5667
{
5768
DocumentId = string.Empty,
@@ -62,6 +73,17 @@ DPS.API.KernelMemory kernelMemory
6273

6374
var result = await kernelMemory.ImportDocument(fileStream, file.FileName, contentType);
6475

76+
// Track successful document import
77+
telemetryHelper.TrackEvent("DocumentImportSuccess", new Dictionary<string, string>
78+
{
79+
{ "documentId", result.DocumentId },
80+
{ "mimeType", result.MimeType ?? "unknown" },
81+
{ "fileSize", file.Length.ToString() }
82+
});
83+
84+
// Set correlation ID for tracing
85+
telemetryHelper.SetActivityTag("documentId", result.DocumentId);
86+
6587
//Return HTTP 202 with Location Header
6688
//return Results($"/Documents/CheckProcessStatus/{result.DocumentId}", result);
6789
// Add Document to the Repository
@@ -72,29 +94,54 @@ DPS.API.KernelMemory kernelMemory
7294
catch (IOException ex)
7395
{
7496
// Log the exception
75-
app.Logger.LogError(ex, "An error occurred while uploading the document.");
97+
logger.LogError(ex, "An error occurred while uploading the document");
98+
telemetryHelper.TrackException(ex, new Dictionary<string, string>
99+
{
100+
{ "endpoint", "/Documents/ImportDocument" },
101+
{ "errorType", "IOException" }
102+
});
76103
throw;
77104
}
78105
catch (Exception ex)
79106
{
80107
// Log the exception
81-
app.Logger.LogError(ex, "An unexpected error occurred.");
108+
logger.LogError(ex, "An unexpected error occurred");
109+
telemetryHelper.TrackException(ex, new Dictionary<string, string>
110+
{
111+
{ "endpoint", "/Documents/ImportDocument" },
112+
{ "errorType", ex.GetType().Name }
113+
});
82114
throw;
83115
}
84116

85117
})
86118
.DisableAntiforgery();
87119

88120
app.MapDelete("/Documents/{documentId}", async (string documentId,
89-
DPS.API.KernelMemory kernelMemory) =>
121+
DPS.API.KernelMemory kernelMemory,
122+
TelemetryHelper telemetryHelper,
123+
ILogger<KernelMemory> logger) =>
90124
{
91125
try
92126
{
93127
await kernelMemory.DeleteDocument(documentId);
128+
129+
telemetryHelper.TrackEvent("DocumentDeleteSuccess", new Dictionary<string, string>
130+
{
131+
{ "documentId", documentId }
132+
});
133+
94134
return Results.Ok(new DocumentDeletedResult() { IsDeleted = true });
95135
}
96136
catch (Exception ex)
97137
{
138+
logger.LogError(ex, "Error deleting document: {DocumentId}", documentId);
139+
telemetryHelper.TrackException(ex, new Dictionary<string, string>
140+
{
141+
{ "endpoint", "/Documents/{documentId}" },
142+
{ "documentId", documentId },
143+
{ "errorType", ex.GetType().Name }
144+
});
98145
return Results.BadRequest(new DocumentDeletedResult() { IsDeleted = false });
99146
}
100147
})

App/backend-api/Microsoft.GS.DPS.Host/DependencyConfiguration/ServiceDependencies.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ public static void Inject(IHostApplicationBuilder builder)
2222
{
2323
builder.Services
2424
.AddValidatorsFromAssemblyContaining<PagingRequestValidator>()
25+
.AddSingleton<TelemetryHelper>()
2526
.AddSingleton<Microsoft.GS.DPS.API.KernelMemory>()
2627
.AddSingleton<Microsoft.GS.DPS.API.ChatHost>()
2728
.AddSingleton<Microsoft.GS.DPS.API.UserInterface.Documents>()

0 commit comments

Comments
 (0)