Reputation: 6085
I want to retrieve some performance counters for the 'ASP.NET Applications' category from within my ASP.NET application.
My problem is, that I don't know how to determine the correct instance name for my current running ASP.NET application.
I currently use this code:
string instanceName = GetCurrentProcessInstanceName();
_perfCounters.Add(new PerformanceCounter("ASP.NET", "Application Restarts"));
_perfCounters.Add(new PerformanceCounter("ASP.NET Applications", "Pipeline Instance Count", instanceName));
_perfCounters.Add(new PerformanceCounter("ASP.NET Applications", "Requests Executing", instanceName));
_perfCounters.Add(new PerformanceCounter("ASP.NET Applications", "Requests/Sec", instanceName));
_perfCounters.Add(new PerformanceCounter("ASP.NET Applications", "Requests Failed", instanceName));
For GetCurrentProcessInstanceName I defined those helper methods from information and code snippets I found on the intertubes:
private static string GetCurrentProcessInstanceName()
{
return GetProcessInstanceName(GetCurrentProcessId());
}
private static int GetCurrentProcessId()
{
return Process.GetCurrentProcess().Id;
}
private static string GetProcessInstanceName(int pid)
{
PerformanceCounterCategory cat = new PerformanceCounterCategory("Process");
string[] instances = cat.GetInstanceNames();
foreach (string instance in instances)
{
using (PerformanceCounter cnt = new PerformanceCounter("Process", "ID Process", instance, true))
{
int val = (int) cnt.RawValue;
if (val == pid)
{
return instance;
}
}
}
return null;
}
Now the problem is, that I get the following error: Instance 'w3wp' does not exist in the specified Category.
So obviously, the code snippets don't return the correct instance ID for the current application.
My question is: How can I determine (reliable) the correct value?
Additional information: Since I learned that one should initially create a performance counter object and re-use this instance (vs. creating this object on every occasion you need this) I fire up a singleton when the application starts up. Out of this reason, I don't have access to a current HttpRequest, since this happens before a request hits the application.
Upvotes: 4
Views: 2713
Reputation: 6085
I found the solution, and it's quite simpel:
string curentWebApplicationInstanceName = System.Web.Hosting.HostingEnvironment.ApplicationID.Replace('/', '_');
Upvotes: 4