Stiamo utilizzando Owin su Azure per un servizio REST e dobbiamo segnalare direttamente a Application Insights. Vogliamo registrare eccezioni e richieste. In questo momento abbiamo questo:Come collegare le eccezioni alle richieste in Application Insights su Azure?
using AppFunc = Func<IDictionary<string, object>, Task>;
public class InsightsReportMiddleware
{
readonly AppFunc next;
readonly TelemetryClient telemetryClient;
public InsightsReportMiddleware(AppFunc next, TelemetryClient telemetryClient)
{
if (next == null)
{
throw new ArgumentNullException("next");
}
this.telemetryClient = telemetryClient;
this.next = next;
}
public async Task Invoke(IDictionary<string, object> environment)
{
var sw = new Stopwatch();
sw.Start();
await next(environment);
sw.Stop();
var ctx = new OwinContext(environment);
var rt = new RequestTelemetry(
name: ctx.Request.Path.ToString(),
timestamp: DateTimeOffset.Now,
duration: sw.Elapsed,
responseCode: ctx.Response.StatusCode.ToString(),
success: 200 == ctx.Response.StatusCode
);
rt.Url = ctx.Request.Uri;
rt.HttpMethod = ctx.Request.Method;
telemetryClient.TrackRequest(rt);
}
}
public class InsightsExceptionLogger : ExceptionLogger
{
readonly TelemetryClient telemetryClient;
public InsightsExceptionLogger(TelemetryClient telemetryClient)
{
this.telemetryClient = telemetryClient;
}
public override Task LogAsync(ExceptionLoggerContext context, System.Threading.CancellationToken cancellationToken)
{
telemetryClient.TrackException(context.Exception);
return Task.FromResult<object>(null);
}
public override void Log(ExceptionLoggerContext context)
{
telemetryClient.TrackException(context.Exception);
}
}
sono registrati alla nostra applicazione in questo modo:
static void ConfigureInsights(IAppBuilder app, HttpConfiguration config)
{
var rtClient = new TelemetryClient();
app.Use<InsightsReportMiddleware>(rtClient);
config.Services.Add(typeof (IExceptionLogger), new InsightsExceptionLogger(rtClient));
}
Questo funziona, tranne le eccezioni e le richieste non sono collegati. Entrambe vengono registrate, ma quando si fa clic su una richiesta non riuscita si dice "Non sono state trovate eccezioni correlate". Al contrario, quando si aprono le proprietà di un'eccezione, è possibile leggere "Richieste interessate da questa eccezione: 0". Qual è il modo corretto per farlo?
"OperationIdTelemetryInitializer, che imposta ITelemetry.Context.Operation.Id con RequestTelemetry.Id estratto dall'ambiente" hai un'idea di come farlo in OWIN?L'implementazione di AspNet alla fine fa 'httpContextAccessor.HttpContext.RequestServices.GetService()'. Come può accedere ad un ambito, contesto locale da un singleton globale? Come può supportare richieste asincrone simultanee? –
trethaller