[ASP.NET] HTTP サーバのイベントをログに残す方法

この記事は3年以上前に書かれた記事です。情報が古い可能性があります。

ASPX でイベントログを記録するには、IHttpModule インタフェースを持つモジュールクラスを作れば良い。

using System;
using System.Web;

namespace Sample 
{
    public class HttpLoggerModule : IHttpModule
    {
        public HttpLoggerModule() : base() 
        {
        }
        
        public void Init(HttpApplication application) 
        {
            // TODO: ここで取得したいイベントハンドラを追加する。
            application.BeginRequest += (new EventHandler(this.Application_BeginRequest));
            application.EndRequest += (new EventHandler(this.Application_EndRequest));
        }
        
        public void Dispose() 
        {
            // TODO: リソースの解放処理。
        }
        
        private void Application_BeginRequest(Object sender , EventArgs e) 
        {
            HttpContext context = ((HttpApplication)sender).Context;
            
            logger.Debug( "-- BeginRequest" );
            logger.Debug( String.Format( @"URL: ""{0}""", context.Request.Url.ToString() ) );
        }
        
        private void Application_EndRequest(object sender, EventArgs e)
        {
            logger.Debug( "-- EndRequest" );
        }
    }
}

上のようなクラスをつくったら、.NET クラスライブラリとしてコンパイル。 HttpLoggerModule.dll というようなバイナリファイルができるので、 これを使うアプリケーションのプロジェクトで、参照設定に追加する。

あとは、そのアプリケーションの web.config に、このモジュールを使うぞ、という設定をする。

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.web>
    <httpModules>
      <add name="HttpLoggerModule" type="Sample.HttpLoggerModule, HttpLoggerModule" />
    </httpModules>
  </system.web>
</configuration>

※参考:[ASP.NET]アプリケーション共通のロギングを行うには?

タイトルとURLをコピーしました