Skip to content

Instantly share code, notes, and snippets.

@mscottreed
Last active November 28, 2015 18:36
Show Gist options
  • Save mscottreed/9fd2cf57e46216cb6461 to your computer and use it in GitHub Desktop.
Save mscottreed/9fd2cf57e46216cb6461 to your computer and use it in GitHub Desktop.
EF Logging
public void TestIndex()
{
var memoryTarget = TestLoggingExtensions.SetupNLogMemoryTarget();
var controller = new PollsController();
controller.Index();
Approvals.VerifyAll(memoryTarget.Logs.FilterOutMigrationLogs(), "log");
}
public class CommandsOnlyFormatter : DatabaseLogFormatter
{
public CommandsOnlyFormatter(DbContext context, Action<string> writeAction)
: base(context, writeAction)
{
}
public override void Opened(
DbConnection connection, DbConnectionInterceptionContext interceptionContext)
{
}
public override void LogCommand<TResult>(
DbCommand command, DbCommandInterceptionContext<TResult> interceptionContext)
{
var dbParameters = command.Parameters.OfType<DbParameter>().ToArray();
if (dbParameters.Any())
{
Write(string.Join(Environment.NewLine, dbParameters.Select(FormatParameter))
+ Environment.NewLine
+ command.CommandText);
}
else
{
Write(command.CommandText);
}
}
private static string FormatParameter(DbParameter p)
{
var sqlParam = p as SqlParameter;
var value = p.Value;
if (p.Value == DBNull.Value || p.Value == null)
{
value = "null";
}
else if (p.DbType == DbType.String || p.DbType == DbType.StringFixedLength)
{
value = string.Format("'{0}'", value);
}
if (sqlParam == null)
{
return string.Format("-- {0}={1} ({2})", p.ParameterName, value, p.DbType);
}
return string.Format("declare @{0} {1} = {2};", p.ParameterName, sqlParam.SqlDbType, value);
}
public override void Closed(
DbConnection connection, DbConnectionInterceptionContext interceptionContext)
{
}
public override void LogResult<TResult>(
DbCommand command, DbCommandInterceptionContext<TResult> interceptionContext)
{
}
}
public class CustomDbConfiguration : DbConfiguration
{
public CustomDbConfiguration()
{
SetDatabaseLogFormatter((c, wa) => new CommandsOnlyFormatter(c, wa));
}
}
static Logger logger = LogManager.GetLogger("PollsContext");
private PollsContext pollsContext;
public EfPollsRepository()
{
pollsContext = new PollsContext();
pollsContext.Database.Log = s => logger.Debug(s);
}
public static class TestLoggingExtensions
{
public static IEnumerable<string> FilterOutMigrationLogs(this IEnumerable<string> logs)
{
return logs.Where(l => !l.Contains("__MigrationHistory") && !l.Contains("EdmMetadata"));
}
public static MemoryTarget SetupNLogMemoryTarget()
{
var config = new LoggingConfiguration();
var memoryTarget = new MemoryTarget { Layout = "${message}" };
config.AddTarget("memory", memoryTarget);
var ruleDebug = new LoggingRule("*", LogLevel.Debug, memoryTarget);
config.LoggingRules.Add(ruleDebug);
LogManager.Configuration = config;
return memoryTarget;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment