I’ve been involving in some tracing work today where we wanted to make sure each request had a correlation id.
Rather than inventing our own number, I wanted to use the request id that IIS already uses internally. This allows us to correlate across even more log files.
Here’s the totally unintuitive code that you need to use to retrieve this value:
var serviceProvider = (IServiceProvider)HttpContext.Current; var workerRequest = (HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest)); var traceId = workerRequest.RequestTraceIdentifier;
(A major motivator for this post was to save me having to trawl back to my sent emails from 2009 the next time I need this code.)
Update 28th Feb 2013: Some people have been seeing Guid.Empty when querying this property. The trace identifier is only available if IIS’s ETW mechanism is enabled. See http://www.iis.net/configreference/system.webserver/httptracing for details on how to enable IIS tracing. Thanks to Levi Broderick from the ASP.NET team for adding this.
Looks like a good thing to extend:
public static class HttpContextExtensions
{
public static Guid GetRequestTraceIdentifier(this HttpContext context)
{
var provider = (IServiceProvider)HttpContext.Current;
var workerRequest = (HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest));
return workerRequest.RequestTraceIdentifier;
}
}
Is there something I need to do to IIS to enable this? I’m getting Guid.Empty backkk
Hmm. Which version of IIS? Which version of ASP.NET? Integrated or classic mode?
Interesting, is it because there’s something special you can do with that ID later? i.e. where does IIS use that trace identifier? Or was it purely to avoid inventing your own number?
It’s used throughout all of the ETW outputs.