LINQ to SQL log to debug window, file, memory or multiple writers

The Log property on a LINQ to SQL data context takes a TextWriter and streams out details of the SQL statements and parameters that are being generated and sent to the server.

Normally in examples you will see Console.Out being assigned to it which is fine for small demos and sandboxes but sooner or later you’ll want access to it in Windows or web applications. Here are some examples of how to redirect TextWriter output such as the DataContext log to other destinations.

GitHub has the latest version of ActionTextWriter etc.

To the output/debug window

The output/debug window mechanism actually uses a listener mechanism and so doesn’t actually directly expose a TextWriter interface however we can simply wrap up Debug.Write in something that does and use that instead:

class DebugTextWriter : System.IO.TextWriter {
   public override void Write(char[] buffer, int index, int count) {
       System.Diagnostics.Debug.Write(new String(buffer, index, count));
   }

   public override void Write(string value) {
       System.Diagnostics.Debug.Write(value);
   }

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

To use it then simply:

myDataContext.Log = new DebugTextWriter();

To a file

#if DEBUG
 db.Log = new System.IO.StreamWriter("linq-to-sql.log") { AutoFlush = true };
#endif

If you wish to not overwrite the existing log file then change the constructor to include the parameter true after the filename. Bear in mind this log file can get very large and slow down your application with all that extra writing to disk and could well reveal information you’d rather wasn’t persisted there so the DEBUG conditional is recommended.

To memory

#if DEBUG
 var sw = new System.IO.StringWriter();
 db.Log = sw;
#endif

You will be able to examine sw or call ToString() on it to see the contents. Again this is not recommended for production as it will cause a lot of memory consumption as the StringWriter gets larger and larger.

To multiple writers

Here is a small useful class that lets you send the results intended for a TextWriter off into multiple writers.

class MulticastTextWriter : TextWriter {
  private readonly IList<TextWriter> textWriters;

  public MulticastTextWriter() : this(new List<TextWriter>()) {
  }

  public MulticastTextWriter(IList<TextWriter> textWriters) {
    this.textWriters = textWriters;
  }

  public void Add(TextWriter textWriter) {
    lock (textWriters)
      textWriters.Add(textWriter);
  }

  public bool Remove(TextWriter textWriter) {
    lock (textWriters)
      return textWriters.Remove(textWriter);
  }

  public override void Write(char[] buffer, int index, int count) {
    lock (textWriters)
      foreach (TextWriter textWriter in textWriters)
        textWriter.Write(buffer, index, count);
  }

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

So if you wanted to output to a log and also to the debug window, you would use it like this (again recommended only for debugging):

var mw = new MulticastTextWriter();
mw.Add(new DebugTextWriter());
mw.Add(new System.IO.StreamWriter("linq-to-sql.log") { AutoFlush = true });
db.Log = mw;

Anything you want

To wrap things up here is a small TextWriter that lets you go off and do whatever you like with the string via the Action delegate.

class ActionTextWriter : TextWriter {
  private readonly 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; }
  }
}

So if you wanted to output all log information to say a WinForms message box a tiny lambda expression gets you there:

db.Log = new ActionTextWriter(s => MessageBox.Show(s));

Have fun!

[)amien

7 responses to LINQ to SQL log to debug window, file, memory or multiple writers

  1. Avatar for

    Information is only used to show your comment. See my Privacy Policy.

  2. Avatar for Damien Guard

    It will not. There should be no harm in leaving it there but the easiest way to turn off entirely would be to put #if DEBUG #endif around the line that connects it to what it is logging.

  3. Avatar for Rubberduck

    Fantastic! Love it. Question though, if you happen to know, will the DebugWriter basically get compiled away in release mode?

  4. Avatar for Júlio Nobre
    Júlio Nobre

    Another great article, specially the ActionTextriter tip.

    To improve it I would like to suggest you to prefix sample classes with public clause — a minor catch to newbies ;-)

  5. Avatar for Karl

    Yes, great article. I had spent most of yesterday playing around with SQL Profiler just to end up with the same result as this solution only less conveniently.

    Thanks very much.

  6. Avatar for Thiago leite
    Thiago leite

    These are very cool and useful. Thanks for sharing.

  7. Avatar for Smit

    How do I also log the parameter values?