Chizh
Chizh

Reputation: 1029

Question about private fields of an IHttpModule implementation

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?

Upvotes: 1

Views: 50

Answers (0)

Related Questions