Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

log LINQ-to-SQL generated SQL to NLog

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?

like image 1000
Coppermill Avatar asked Oct 05 '09 16:10

Coppermill


1 Answers

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; }
  }
}
like image 132
DamienG Avatar answered Oct 21 '22 11:10

DamienG