要专业系统地学习EF推荐《你必须掌握的Entity Framework 6.x与Core 2.0》。这本书作者(汪鹏,Jeffcky)的博客:https://www.cnblogs.com/CreateMyself/
格式化日志输出
上次我们知道了利用ctx.Database.Log来进行简单的日志打印,还是很有帮助的。
那么它其实是继承自DatabaseLogFormatter,那么我们可以写一个派生自DatabaseLogFormatter这个类,来实现更多的自定义操作
实现步骤
1 写一个派生自DatabaseLogFormatter的类
2.在EF中进行注册
又到了学英语的时候,看一下DatabaseLogFormatter
我来重写LogCommad 和Closing方法,因为对里面的东西都不熟,所以我都打印看一下
public class DBlogFormatter : DatabaseLogFormatter { public DBlogFormatter(DbContext context, Action<string> writeAction) : base(context, writeAction) { } public override void LogCommand<TResult>(DbCommand command, DbCommandInterceptionContext<TResult> interceptionContext) { Write($"重写LogCommand:记录将要执行的命令:command.CommandText:{command.CommandText}{Environment.NewLine}" + $"command.CommandTimeout:{command.CommandTimeout}{Environment.NewLine}" + $"command.CommandType:{command.CommandType}{Environment.NewLine}" + $"command.Connection:{command.Connection}{Environment.NewLine}" + $"command.Container:{command.Container}{Environment.NewLine}" + $"command.Parameters:{command.Parameters}{Environment.NewLine}" + $"command.Site:{command.Site}{Environment.NewLine}" + $"command.ToString():{command.ToString()}{Environment.NewLine}" + $"command.Transaction:{command.Transaction}{Environment.NewLine}" + $"command.UpdateRowSource:{command.UpdatedRowSource}{Environment.NewLine}"); } public override void Closing(DbConnection connection, DbConnectionInterceptionContext interceptionContext) { Write($"重写Closing:{Environment.NewLine}" + $"connection.ConnectinoString:{connection.ConnectionString}{Environment.NewLine}" + $"connection.ConnectionTimeout:{connection.ConnectionTimeout}{Environment.NewLine}" + $"connection.Container:{connection.Container}{Environment.NewLine}" + $"connection.Database:{connection.Database}{Environment.NewLine}" + $"connection.DataSource:{connection.DataSource}{Environment.NewLine}" + $"connection.ServerVersion:{connection.ServerVersion}{Environment.NewLine}" + $"connection.Site:{connection.Site}{Environment.NewLine}"); base.Closing(connection, interceptionContext); } }