Advertisement
Guest User

Untitled

a guest
Jan 11th, 2011
410
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.90 KB | None | 0 0
  1. public class BaseModule : IHttpModule
  2. {
  3.     private const double Treshold = 5;
  4.     private string _filePath;
  5.  
  6.     public void Init(HttpApplication context)
  7.     {
  8.         _filePath = System.Web.Hosting.HostingEnvironment.MapPath("~/App_Data");
  9.  
  10.         context.PreRequestHandlerExecute += PreRequestHandler;
  11.         context.PostRequestHandlerExecute += PostRequestHandler;
  12.     }
  13.  
  14.     public void Dispose()
  15.     {
  16.        
  17.     }
  18.  
  19.     protected void PreRequestHandler(object sender, EventArgs e)
  20.     {
  21.         var requestContext = ((HttpApplication)sender).Context;
  22.  
  23.         var timer = new Stopwatch();
  24.  
  25.         // Store timer in request
  26.         requestContext.Items["Timer"] = timer;
  27.         timer.Start();
  28.     }
  29.  
  30.     protected void PostRequestHandler(object sender, EventArgs e)
  31.     {
  32.         var requestContext = ((HttpApplication)sender).Context;
  33.  
  34.         var timer = requestContext.Items["Timer"] as Stopwatch;
  35.         if (timer == null)
  36.             return;
  37.  
  38.         timer.Stop();
  39.  
  40.         var elapsedSeconds = timer.Elapsed.Seconds;
  41.         if(elapsedSeconds > Treshold)
  42.         {
  43.             // Log slow running page
  44.             File.AppendAllText(Path.Combine(_filePath, "slow-loading.txt"), GetWarning(requestContext, elapsedSeconds));
  45.         }
  46.     }
  47.  
  48.     protected string GetWarning(HttpContext context, double elapsedSeconds)
  49.     {
  50.         var sb = new StringBuilder();
  51.         sb.AppendLine(string.Format("[{0}] [{1} seconds] ({2} {3}) ", DateTime.Now, elapsedSeconds, context.Request.HttpMethod, context.Request.Url));
  52.  
  53.         if(context.Request.HttpMethod == "POST")
  54.         {
  55.             for(var i = 0; i < context.Request.Form.Count; i++)
  56.             {
  57.                 sb.AppendLine(string.Format("{0}: {1}", context.Request.Form.GetKey(i), context.Request.Form[i]));
  58.             }
  59.         }
  60.  
  61.         sb.AppendLine("-------------");
  62.         return sb.ToString();
  63.     }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement