WebApi2官网学习记录---Tracing

安装追踪用的包

Install-Package Microsoft.AspNet.WebApi.Tracing
Update-Package Microsoft.AspNet.WebApi.WebHost   //-Version指定具体的版本

启用追踪的功能(在WebApiConfig.cs中)

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config) { SystemDiagnosticsTraceWriter traceWriter =config.EnableSystemDiagnosticsTracing(); traceWriter.IsVerbose = true;//显示详情信息 traceWriter.MinimumLevel = TraceLevel.Debug;//追踪的最低级别  } }

在webapi中添加追踪

using System.Web.Http.Tracing;

public class ProductsController : ApiController { public HttpResponseMessage GetAllProducts() { Configuration.Services.GetTraceWriter().Info( Request, "ProductsController", "Get the list of products."); // ...  } }

通过实现ITraceWriter 接口自定义一个trace,也可以使用第三方的类库

public class SimpleTracer : ITraceWriter
{
    public void Trace(HttpRequestMessage request, string category, TraceLevel level, Action<TraceRecord> traceAction) { TraceRecord rec = new TraceRecord(request, category, level); traceAction(rec); WriteTrace(rec); } protected void WriteTrace(TraceRecord rec) { var message = string.Format("{0};{1};{2}", rec.Operator, rec.Operation, rec.Message); System.Diagnostics.Trace.WriteLine(message, rec.Category); } } //启用自定义的trace public static void Register(HttpConfiguration config) { config.Services.Replace(typeof(ITraceWriter), new SimpleTracer()); }

只有一个trace writer可以被激活使用,默认情况下使用一个什么都不做的trace writer。

 

你可能感兴趣的:(Trac)