Logga SqlCommand till NLog

Eftersom det dyker upp en del SqlCommand i koden ibland, så slängde jag ihop en liten logg-funktion för det också:

[Conditional("DEBUG")]
internal static void ToNLog(this DbCommand command, NLog.Logger logger)
{
	logger.Trace("Command: '{0}', Type: {1}", command.CommandText, command.CommandType);

	foreach (DbParameter parameter in command.Parameters)
	{
		logger.Trace("Parameter: ['{0}', '{1}', '{2}', '{3}', '{4}']",
		             parameter.ParameterName,
		             parameter.Value,
		             parameter.Direction,
		             parameter.DbType,
		             parameter.Size);
	}
}

Som synes är det en extension till DbCommand och anropas enligt följande:

private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();

private readonly string _connectionString;

public SomeClass(string connectionString)
{
	_connectionString = connectionString;
}

private int SomeFunction()
{
	const string sql = @"SELECT * FROM dbo.SomeTable WHERE SomeColumn = @SomeParam";

	using (var connection = new SqlConnection(_connectionString))
	using (var command = new SqlCommand(sql, connection))
	{
		command.Parameters.Add("@SomeParam", SqlDbType.VarChar, 10).Value = "SomeValue";

		command.ToNLog(Logger);

		if (command.Connection.State != ConnectionState.Open)
			command.Connection.Open();

		return (int)command.ExecuteScalar();
	}
}

leave your comment