-
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathCommandLogger.cs
More file actions
55 lines (50 loc) · 1.86 KB
/
Copy pathCommandLogger.cs
File metadata and controls
55 lines (50 loc) · 1.86 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
48
49
50
51
52
53
54
55
using Npgsql;
namespace NpgsqlRest;
/// <summary>
/// Helper class for logging SQL command executions at Trace level.
/// Use this when a command is about to be executed.
/// For configuration logging (endpoints, SQL command templates), use regular Logger.LogDebug.
/// </summary>
public static class CommandLogger
{
/// <summary>
/// Logs a command execution at Trace level. Call this immediately before executing a command.
/// </summary>
/// <param name="command">The NpgsqlCommand to log.</param>
/// <param name="logger">The logger to use.</param>
/// <param name="name">The name/context of the operation (e.g., "PasskeyAuth.Login", "RoutineSource").</param>
public static void LogCommand(NpgsqlCommand command, ILogger? logger, string name)
{
if (logger?.IsEnabled(LogLevel.Trace) != true)
{
return;
}
var sb = StringBuilderPool.Rent();
try
{
for (int i = 0; i < command.Parameters.Count; i++)
{
sb.Append('$');
sb.Append(i + 1);
sb.Append('=');
sb.AppendLine(PgConverters.SerializeDatbaseObject(command.Parameters[i].Value));
}
sb.Append(command.CommandText);
logger.LogTrace("{name}:\n{query}", name, sb.ToString());
}
finally
{
StringBuilderPool.Return(sb);
}
}
/// <summary>
/// Extension method for NpgsqlCommand to log command execution at Trace level.
/// Uses the static Logger from NpgsqlRestOptions.
/// </summary>
/// <param name="command">The NpgsqlCommand to log.</param>
/// <param name="name">The name/context of the operation.</param>
public static void LogCommand(this NpgsqlCommand command, string name)
{
LogCommand(command, NpgsqlRestOptions.Logger, name);
}
}