Starting a new large-scale project with an ASP.NET front-end, I wanted to add a mechanism to get constant feedback about what my app was doing. Something similar to the built-in tracing mechanism, but far more lightweight. <%@Page trace="true"...%> is great for specific cases, but it probably isn't something you want to leave on all the time while developer - and even if you do, there's so much noise you might miss out on those vital pieces of information.
So after googling around for a good solution and being surprised that I couldn't find anything, I decided to write my own. I can't help but think that there's a well known solution that everyone (but me) uses, so if there is, please tell me! Otherwise here are the very simple steps to reproduce what I have so far.
The approach is simple: store log messages in a List within then HttpContext, and dump it to the page. First, we start off with the class that'll hold each trace message. Within this class we'll hold the actual message, a type (log, debug, error), the elapsed time in milliseconds from the first logged message and the delta in milliseconds from the previous message:
public class TracerItem { public TracerItemType Type { get; set; } public DateTime Dated { get; set; } public string Message { get; set; } public int Delta { get; set; } public int Elapsed { get; set; } public TracerItem() {} public TracerItem(DateTime dated, TracerItemType type, string message, int elapsed, int delta) { Dated = dated; Type = type; Message = message; Elapsed = elapsed; Delta = delta; } } public enum TracerItemType { Info = 1, Debug = 2, Error = 3, }
There's really nothing to explain there. Next, we'll create our static Tracer class, which defined the very important Log method:
public static class Tracer { public static List<TracerItem> GetLogs() { var items = (List<TracerItem>) HttpContext.Current.Items["__tracer"]; if (items == null) { items = new List<TracerItem>(); HttpContext.Current.Items["__tracer"] = items; } return items; } public static void Log(string message, params object[] arguments) { #if TRACER Log(message, TracerType.Info, arguments);
No comments:
Post a Comment
Post your comments here: