Created
July 2, 2014 20:40
-
-
Save csainty/d38b42e06bcdbba56ff9 to your computer and use it in GitHub Desktop.
TracingMiddleware.cs for @jchannon
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace TracingMiddleware | |
{ | |
using System; | |
using System.Diagnostics; | |
using System.IO; | |
using System.Linq; | |
using System.Text; | |
using MidFunc = System.Func< | |
System.Func<System.Collections.Generic.IDictionary<string, object>, System.Threading.Tasks.Task>, | |
System.Func<System.Collections.Generic.IDictionary<string, object>, System.Threading.Tasks.Task> | |
>; | |
public static class TracingMiddleware | |
{ | |
public static MidFunc Tracing(TracingMiddlewareOptions tracingMiddlewareOptions = null) | |
{ | |
tracingMiddlewareOptions = tracingMiddlewareOptions ?? new TracingMiddlewareOptions(); | |
return | |
next => | |
async environment => | |
{ | |
using (var capturingStream = new MemoryStream()) | |
{ | |
var capturedStream = (Stream)environment["owin.ResponseBody"]; | |
environment["owin.ResponseBody"] = capturingStream; | |
var stopWatch = new Stopwatch(); | |
tracingMiddlewareOptions.Interpreter.Interpret("Request Start", ""); | |
var requestItems = | |
environment.Where(x => x.Key.StartsWith("owin.request", StringComparison.OrdinalIgnoreCase)); | |
foreach (var item in requestItems) | |
{ | |
tracingMiddlewareOptions.Interpreter.Interpret(item.Key, item.Value); | |
} | |
stopWatch.Start(); | |
await next(environment); | |
stopWatch.Stop(); | |
capturingStream.Seek(0, SeekOrigin.Begin); | |
var bytes = capturingStream.ToArray(); | |
await capturedStream.WriteAsync(bytes, 0, bytes.Length); | |
var responseItems = | |
environment.Where(x => !x.Key.StartsWith("owin.request", StringComparison.OrdinalIgnoreCase)); | |
foreach (var item in responseItems) | |
{ | |
tracingMiddlewareOptions.Interpreter.Interpret(item.Key, item.Value); | |
} | |
tracingMiddlewareOptions.Interpreter.Interpret("Response", Encoding.UTF8.GetString(bytes)); | |
tracingMiddlewareOptions.Interpreter.Interpret("Request Finished", ""); | |
tracingMiddlewareOptions.Interpreter.Interpret("Execution Time", stopWatch.ElapsedMilliseconds); | |
} | |
}; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment