2017-08-03 18 views
3

私はすべてのリクエストを自動的に記録したいと思います。以前の.Net Framwork WebAPIプロジェクトでは、私はdelegateHandlerを登録していました。ログの内容の.NET Core WebAPIのすべての要求を自動ログに記録する方法は?

WebApiConfig.cs

public static void Register(HttpConfiguration config) 
{ 
    config.MessageHandlers.Add(new AutoLogDelegateHandler()); 
} 

AutoLogDelegateHandler.cs

public class AutoLogDelegateHandler : DelegatingHandler 
{ 

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) 
    { 
     var requestBody = request.Content.ReadAsStringAsync().Result; 

     return await base.SendAsync(request, cancellationToken) 
      .ContinueWith(task => 
      { 
       HttpResponseMessage response = task.Result; 

       //Log use log4net 
       _LogHandle(request, requestBody, response); 

       return response; 
      }); 
    } 
} 

例:

------------------------------------------------------ 
2017-08-02 19:34:58,840 
uri: /emp/register 
body: { 
    "timeStamp": 1481013427, 
    "id": "0322654451", 
    "type": "t3", 
    "remark": "system auto reg" 
} 
response: {"msg":"c556f652fc52f94af081a130dc627433","success":"true"} 
------------------------------------------------------ 

しかし、.NETのコアWebAPIのプロジェクトでは、何のWebApiConfigはありません、またはGlobal.asaxのレジスタ関数GlobalConfiguration.Configure(WebApiConfig.Register);

.NET Core WebAPIでこれを達成する方法はありますか?

答えて

4
あなたが独自のフィルタ属性を作成することができます

...

public class InterceptionAttribute : ActionFilterAttribute 
{ 
    public override void OnActionExecuting(HttpActionContext actionContext) 
    { 
    var x = "This is my custom line of code I need executed before any of the controller actions, for example log stuff"; 
    base.OnActionExecuting(actionContext); 
    } 
} 

...そして、あなたはGlobalFiltersに登録だろうが、あなたは.NETのコアを使用していると述べたことから、これはあなたが試すことができる方法であります先に進む... docs.microsoft.comから

あなたは(すべてのコントローラとアクションのための)グローバルフィルタを登録することができ MvcOptions.Filtersにそれを追加することにより、収集イオンは、Startupクラスの ConfigureServicesメソッドにあります。

私はそれが働いている場合はお知らせください。

P.S. 詳細については、whole tutorial on intercepting requests with WebAPIをご覧ください。

+3

はい、それは動作します。私は 'AutoLogAttribute'を作成し、すべてのリクエストを' OnActionExecuted'に記録します。 StartupクラスのConfigureServicesメソッドのMvcOptions.Filtersコレクションにフィルターを追加して、フィルターをグローバルに登録します。 – wtf512

+0

恐ろしいですが、うまくいきました – Eedoh

+0

正解は、すでにあなたのために記録されています。 – davidfowl

0

デモ:あなたはMVCミドルウェアによって処理のみ要求をログに記録する必要があるまで

/// <summary> 
/// <see cref="https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/filters#Dependency injection"/> 
/// </summary> 
public class AutoLogAttribute : TypeFilterAttribute 
    { 
     public AutoLogAttribute() : base(typeof(AutoLogActionFilterImpl)) 
     { 

     } 

     private class AutoLogActionFilterImpl : IActionFilter 
     { 
      private readonly ILogger _logger; 
      public AutoLogActionFilterImpl(ILoggerFactory loggerFactory) 
      { 
       _logger = loggerFactory.CreateLogger<AutoLogAttribute>(); 
      } 

      public void OnActionExecuting(ActionExecutingContext context) 
      { 
       // perform some business logic work 
      } 

      public void OnActionExecuted(ActionExecutedContext context) 
      { 
       //TODO: log body content and response as well 
       _logger.LogDebug($"path: {context.HttpContext.Request.Path}"); 
      } 
     } 
    } 

StartUp.cs

public void ConfigureServices(IServiceCollection services) 
{ 
    //.... 

    // https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/filters#filter-scopes-and-order-of-execution 
    services.AddMvc(opts=> { 
     opts.Filters.Add(new AutoLogAttribute()); 
    }); 

    //.... 
} 
6

ActionFilterが動作する

AutologArribute.cs(新しいファイル) (コントローラアクションとして)。

すべての着信要求のログが必要な場合は、ミドルウェアのアプローチを使用する必要があります。

explanation視覚的なグッド: enter image description here

なお、ミドルウェアの順番は重要であり、あなたのロギングがパイプライン実行の開始時に行われるべきであるならば、あなたのミドルウェアは最初の1のいずれかでなければなりません。 docsから

簡単な例:

public void Configure(IApplicationBuilder app) 
    { 
     app.Use(async (context, next) => 
     { 
      // Do loging 
      // Do work that doesn't write to the Response. 
      await next.Invoke(); 
      // Do logging or other work that doesn't write to the Response. 
     }); 
関連する問題