The Light
The Light

Reputation: 27011

In ASP.NET Web API, how to view the TraceRecord Details on a Built-in Page Nicely?

I've enabled tracing for my Web API application by creating a new Trace Writter which just logs the details in a file:

public class MyTraceWriter : ITraceWriter
{
    private readonly ILog _log;
    public MyTraceWriter(ILog log)
    {
        _log = log;
    }

    public void Trace(HttpRequestMessage request, string category, TraceLevel level, Action<TraceRecord> traceAction)
    {
        var traceRecord = new TraceRecord(request, category, level);
        traceAction(traceRecord);
        _log.Info(GetDetails(traceRecord));
    }

    private string GetDetails(TraceRecord traceRecord)
    {
        var sb = new StringBuilder();
        sb.AppendFormat("\r\n\t{0} {1}\r\n\tCategory={2}, Level={3}, Kind={4}\r\n\tOperator:{5}, Operation: {6}",
                traceRecord.Request.Method,
                traceRecord.Request.RequestUri,
                traceRecord.Category,
                traceRecord.Level,
                traceRecord.Kind,
                traceRecord.Operator,
                traceRecord.Operation);

        if (traceRecord.Exception != null)
        {
            sb.AppendFormat("\r\n\tException : {0}", traceRecord.Exception.GetBaseException().Message);
        }
        else if (traceRecord.Message != null)
        {
            sb.AppendFormat("\r\n\tMessage : {0}", traceRecord.Message);
        }
        sb.AppendLine();
        return sb.ToString();
    }
}

Then registering my class in the Global.ascx:

config.Services.Replace(typeof(ITraceWriter),
                    new MyTraceWriter(LogManager.GetLogger("Tracing")));

I'm just wondering is there any built-in feature/tool/page that I can use/monitor to view the details of the tracing?

if possible, I'd like to avoid creating my own custom database table and page.

Upvotes: 1

Views: 1766

Answers (1)

Kiran
Kiran

Reputation: 57949

You could alternatively install the "Microsoft.AspNet.WebApi.Tracing" nuget package and then call config.EnableSystemDiagnosticsTracing(); in your WebApiConfig.cs. This extension registers the SystemDiagnosticsTraceWriter for you.

You could also register an EventLog trace listener to write events to the EventLog, in which case you can use the EventViewer to view the data.

Example:

<configuration> <system.diagnostics> <trace autoflush="false" indentsize="4"> <listeners> <add name="myListener" type="System.Diagnostics.EventLogTraceListener" initializeData="TraceListenerLog" /> </listeners> </trace> </system.diagnostics>

Upvotes: 2

Related Questions