0

For an application that runs in IIS integrated mode, I'm going to implement System.Web.IHttpModule and I want the implementation to contain a private field that I want to be in "the scope of the request". The following code illustrates my idea:

// SillyErrorLoggingHttpModule.cs
using System;
using System.Web;
using Serilog;

public class SillyErrorLoggingHttpModule : IHttpModule
{
    private ILogger _logger;

    public void Init(HttpApplication context)
    {
        context.BeginRequest += ContextOnBeginRequest;
        context.Error += Context_Error;
        context.EndRequest += (sender, args) => throw new ApplicationException();
    }

    private void ContextOnBeginRequest(object sender, EventArgs e)
    {
        if (sender is HttpApplication application)
        {
            _logger = GetLogger(application);
        }
        else
        {
            throw new ApplicationException("Toto, I've a feeling we're not in Kansas anymore.");
        }
    }

    private void Context_Error(object sender, EventArgs e)
    {
        if (sender is HttpApplication application)
        {
            _logger.Error(application.Server.GetLastError(), "badumtss!");
        }
        else
        {
            _logger.Error("tada-da-da!");
        }
    }

    public void Dispose()
    {
    }

    public ILogger GetLogger(HttpApplication application)
    {
        // something like this:
        return Log.Logger
            .ForContext("url", application.Request.Url)
            .ForContext("requestUUID", Guid.NewGuid().ToString());
    }
}

My goal is to keep the relation between requestUUID property of log message and exception occurred during request for which I have initialized _logger with requestUUID. But...

Can I be sure that there will be no race-condition for the IHttpModule state between requests under the load?

Can I assume that my log messages won't mix-up in this case?

Or, at least, is there some files at referencesource where I can check my assumption?

Chizh
  • 1,019
  • 7
  • 16
  • There can be multiple `HttpApplication` in the same process, each loads an instance of your module. – Lex Li Mar 29 '19 at 15:56
  • yes, but I want to know if instances will not mix up. For ex., if the instance handled begun request event for request A: 1 will it handle application error event for request A as well? and 2 won't it handle begin request event for request B while handling A is still in progress? I know usually I can use application.Contex.Items to pass things between events, but I'd like to be able still match error logs with requests during request_end event handling – Chizh Mar 31 '19 at 08:25
  • @Lex Li or am I getting it wrong and one application instance is "assigned" to handle a request it will stick with it till the end of request? – Chizh Mar 31 '19 at 08:33

0 Answers0