linq-to-sql - 将 LINQ-to-SQL 生成的 SQL 记录到 NLog

标签 linq-to-sql nlog

我想使用 NLog 将我的 LINQ to SQL 生成的 SQL 输出到日志文件

例如
db.Log = Console.Out
将生成的 SQL 报告给控制台,http://www.bryanavery.co.uk/post/2009/03/06/Viewing-the-SQL-that-is-generated-from-LINQ-to-SQL.aspx

如何让日志记录到 NLog?

最佳答案

您只需要一个类来充当 TextWriter,LINQ to SQL 需要通过您想要的方法来调度它,例如

db.Log = new ActionTextWriter(s => logger.Debug(s));

这是我写的一个小文本编写器,它接受一个委托(delegate)并分派(dispatch)给它,所以你可以使用上面的代码。你可能想改变这个类,所以它需要一个记录器,对文本进行一些处理/拆分,然后将它分派(dispatch)给 NLog。
class ActionTextWriter : TextWriter {
  private Action<string> action;

  public ActionTextWriter(Action<string> action) {
    this.action = action;
  }

  public override void Write(char[] buffer, int index, int count) {
    Write(new string(buffer, index, count));
  }

  public override void Write(string value) {
    action.Invoke(value);
  }

  public override Encoding Encoding {
    get { return System.Text.Encoding.Default; }
  }
}

关于linq-to-sql - 将 LINQ-to-SQL 生成的 SQL 记录到 NLog,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1520945/

相关文章:

configuration - 使用 SlowCheetah 进行自定义配置时出现 Azure 辅助角色配置问题

c# - NLog - 扩展 Nlog - callsite - dispose()

.net - 使用 nlog 在控制台应用程序中滚动文件日志

c# - ASP.NET Core 日志记录不适用于生产

c# - LINQ to SQL 连接两个表以根据子表中的两个不同列选择父表两次

Linq-to-sql orderby thenby

linq - 在 LINQ to SQL 中检索单个记录结果的最佳方法

c# - 寻找通用日志记录接口(interface)以在 NuGet 包中创建通用日志记录

c# - LINQ: 'Select c' 和 'Select new (c...' 之间的区别

c# - LINQ 查询中的 InvalidCastException