views:

128

answers:

1

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?

+5  A: 

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; }
  }
}
DamienG
Awesome, thanks :)
Jedidja