Skip to content

Instantly share code, notes, and snippets.

@pinscript
Created August 20, 2015 07:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pinscript/01a3d9e68fae1a143ffc to your computer and use it in GitHub Desktop.
Save pinscript/01a3d9e68fae1a143ffc to your computer and use it in GitHub Desktop.
Log slow loading pages using ASP.NET MVC
public class BaseModule : IHttpModule
{
private const double Treshold = 5;
private string _filePath;
public void Init(HttpApplication context)
{
_filePath = System.Web.Hosting.HostingEnvironment.MapPath("~/App_Data");
context.PreRequestHandlerExecute += PreRequestHandler;
context.PostRequestHandlerExecute += PostRequestHandler;
}
public void Dispose()
{
}
protected void PreRequestHandler(object sender, EventArgs e)
{
var requestContext = ((HttpApplication)sender).Context;
var timer = new Stopwatch();
// Store timer in request
requestContext.Items["Timer"] = timer;
timer.Start();
}
protected void PostRequestHandler(object sender, EventArgs e)
{
var requestContext = ((HttpApplication)sender).Context;
var timer = requestContext.Items["Timer"] as Stopwatch;
if (timer == null)
return;
timer.Stop();
var elapsedSeconds = timer.Elapsed.Seconds;
if(elapsedSeconds > Treshold)
{
// Log slow running page
File.AppendAllText(Path.Combine(_filePath, "slow-loading.txt"), GetWarning(requestContext, elapsedSeconds));
}
}
protected string GetWarning(HttpContext context, double elapsedSeconds)
{
var sb = new StringBuilder();
sb.AppendLine(string.Format("[{0}] [{1} seconds] ({2} {3}) ", DateTime.Now, elapsedSeconds, context.Request.HttpMethod, context.Request.Url));
if(context.Request.HttpMethod == "POST")
{
for(var i = 0; i < context.Request.Form.Count; i++)
{
sb.AppendLine(string.Format("{0}: {1}", context.Request.Form.GetKey(i), context.Request.Form[i]));
}
}
sb.AppendLine("-------------");
return sb.ToString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment