gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 00:49:02 24 4
gpt4 key购买 nike

我想使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com