using Npgsql;
namespace NpgsqlRest;
///
/// 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.
///
public static class CommandLogger
{
///
/// Logs a command execution at Trace level. Call this immediately before executing a command.
///
/// The NpgsqlCommand to log.
/// The logger to use.
/// The name/context of the operation (e.g., "PasskeyAuth.Login", "RoutineSource").
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);
}
}
///
/// Extension method for NpgsqlCommand to log command execution at Trace level.
/// Uses the static Logger from NpgsqlRestOptions.
///
/// The NpgsqlCommand to log.
/// The name/context of the operation.
public static void LogCommand(this NpgsqlCommand command, string name)
{
LogCommand(command, NpgsqlRestOptions.Logger, name);
}
}