Thursday, May 15, 2008

Linq DataContext.Log to Log4Net - Using Log4Net to log the SQL generated by Linq to SQL

CodeProject - Redirect LINQ to SQL DataContext Log Messages To Log4Net

"An article that shows how one can use Log4Net to capture the log messages that are generated by the LINQ to SQL DataContext classes

Visual Studio automatically generates the subclasses of DataContext class when dealing with LINQ to SQL for ORM. These auto generated classes have a property named Log of type System.IO.TextWriter. If an object of type TextWriter or its subclass is assigned to this property, then it will use that instance for writing the log messages. As Log4Net is one of the most used Logging libraries for .NET enterprise level projects, in this project I will present a solution to capture the log messages through Log4Net logging.

Background

In my project, I have a well established logging framework that uses Log4Net. Now that I moved to LINQ to SQL, I needed to get the raw SQL that is generated from the LINQ C# codes for both instrumentation and performance purposes. From MSDN, I came to know that I need to pass an instance of type TextWriter to get the log messages from the DataContext subclasses. So, I ended up writing a subclass of TextWriter called LINQLogger, which encapsulates the responsibility of using Log4Net logger under the hood as it receives the log messages from the DataContext classes.

..."

I like the architecture of this article, with its abstracting out of the logging engine, usage of patterns, etc.

No comments: