I’d like to use SQL Server traces to track more context about what code is using the database. I was going to use the “Application Name” property on the connection string. That looks something like the following:
object CallingObject; //set elsewhere
SqlConnectionStringBuilder connectionString = GetConnectionString();
connectionString.ApplicationName = CallingObject.GetType().ToString();
using (SqlConnection connection = new SqlConnection(connectionString.ToString()))
{
// do your thing
}
Except that the large variety of resulting connection strings would mean that .net’s Connection Pooling is no longer effective.
How can I track calling code in a SQL Trace without losing the benefit of connection pooling?
As long as you’re using SQL Server, and as long as you have (or can have) centralized connection-creation logic, you can use the
CONTEXT_INFOfeature: http://msdn.microsoft.com/en-us/library/ms187768.aspxWe do something like this to track DB connections in a multi-user server-side application. Every time a new DB connection is created (reused from connection pooling, really, but “created” in ADODB/ADO.Net code):
Later, when you want to “track” the connections, you can convert the specified range of the context-info back to VarChar content:
Some considerations:
sp_trace_generateevent, as outlined in this related question: How do you access the Context_Info() variable in SQL2005 Profiler?UPDATE:
Only after re-reading your question did I realize you seem to be explicitly looking to add info to Traces only, and not so much for ad-hoc analysis of your current connections (which is more what I associated the use of “Application Name” with, sorry); the only useful approach I’ve seen specifically is the
sp_trace_generateeventcall. If you’re going to do this, I’d advise you to also add the connection_info, as it won’t cost you any more (you alsready have the db round-trip forsp_trace_generateevent) and will definitely help you with other types of analysis later on.