30
Jul
2008

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.

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 IList textWriters;

    public MulticastTextWriter() {
        textWriters = new List();
    }

    public MulticastTextWriter(IList 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):

   MulticastTextWriter 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 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


5 responses to “LINQ to SQL log to debug window, file, memory or multiple writers”


  1. Gravatar 1 Hilton Giesenow Aug 8th, 2008 at 08:08

    Some great tips, thanks! I'll definitely make use of some of these. One small addition that you could include is logging to the ASP.NET response output stream: http://dotnet.org.za/hiltong/archive/2008/07/16/displaying-linq-to-sql-s-actual-sql-queries-in-your-asp-net-page.aspx

  2. Gravatar 2 Smit Nov 5th, 2008 at 12:11

    How do I also log the parameter values?

  1. 1 Logging LINQ To SQL Queries - Hilton Giesenow's Jumbled Mind Pingback on Aug 8th, 2008 at 08:08
  2. 2 LOG LINQ 2 SQL query execution to console/debug window « {Programming} & Life Pingback on Dec 30th, 2008 at 16:12
  3. 3 David DeWinter » LINQ to SQL: Updating Entities Pingback on Apr 7th, 2009 at 20:04

Leave a reply




Topics