Search code examples
c#sql-serverhttpmodule

Is it possible to write a global HttpModule in IIS and log SQL


Is it possible to write a global HttpModule in IIS and log all SQL request from all .NET applications running? If so where should I start?

I have seen some tools out there like http://newrelic.com that do this. Their tool logs all SQL and does not require me to put any special code in my apps. In fact it logs info from all the apps.


Solution

  • If you are going to log SQL requests, you need one of the following:

    1. A custom data-layer class that you use for all SQL requests, and you can log every call. For example, create a class SQLHelper with method ExecuteQuery that calls SQLCommand.ExecuteQuery, then takes the query passed in and logs it. Then you have to be disciplined in making sure every single SQL call is routed through your helper class.
    2. Using a framework like LINQ-To-SQL or Entity Framework, which has Logging tools built in, for example through the DataContext.Log property.
    3. Use SQL Server Profiler with appropriate settings to capture trace of SQL requests, which can be dumped to file or table for later processing.

    You can't capture all standard ADO.Net SQL requests from a .NET global HTTP Module because you don't have knowledge of or access to all of the current connections and commands that are executing.