I would like to use NLog to output my LINQ to SQL generated SQL to the log file
e.g.
db.Log = Console.Out
reports the generated SQL to the console, http://www.bryanavery.co.uk/post/2009/03/06/Viewing-the-SQL-that-is-generated-from-LINQ-to-SQL.aspx
How can I get the log to log to NLog?
You just need a class to act as a TextWriter that LINQ to SQL needs to dispatch it via the method you want, e.g.
db.Log = new ActionTextWriter(s => logger.Debug(s));
Here is a little text writer I wrote that takes a delegate and dispatches to that so you use the code above. You would probably want to change this class so it took a logger, did some processing/splitting on the text and then dispatched it out to 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; }
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With