-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNpgsqlLoggingExtensions.cs
More file actions
47 lines (39 loc) · 1.21 KB
/
NpgsqlLoggingExtensions.cs
File metadata and controls
47 lines (39 loc) · 1.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
using Microsoft.AspNetCore.Mvc;
using Npgsql;
using OrdersApi.Dtos;
using Microsoft.Extensions.Logging;
using QuestPDF.Fluent;
using QuestPDF.Helpers;
using QuestPDF.Infrastructure;
using System.Text;
using RazorLight;
using System.Diagnostics;
public static class NpgsqlLoggingExtensions
{
public static async Task<NpgsqlDataReader> ExecuteReaderWithLoggingAsync(
this NpgsqlCommand cmd,
ILogger logger)
{
var sql = cmd.CommandText;
var parameters = cmd.Parameters
.Cast<NpgsqlParameter>()
.ToDictionary(p => p.ParameterName, p => p.Value);
var sw = Stopwatch.StartNew();
try
{
logger.LogInformation("SQL: {Sql} | Params: {@Params}", sql, parameters);
var reader = await cmd.ExecuteReaderAsync();
sw.Stop();
logger.LogInformation("SQL executed in {Elapsed} ms", sw.ElapsedMilliseconds);
return reader;
}
catch (Exception ex)
{
sw.Stop();
logger.LogError(ex,
"SQL FAILED: {Sql} | Params: {@Params} | Time: {Elapsed} ms",
sql, parameters, sw.ElapsedMilliseconds);
throw;
}
}
}