Multi-tenant logging in ASP.NET MVC application

谁都会走 提交于 2019-12-05 22:07:44

Do you use an Ioc container in your application? I was able to solve a similar problem using AutoFac MultitenantContainer. Steps that you need to follow

  1. define the strategy you would use to identify each tenant.
  2. Register a generic logger interface with Autofac container
  3. For each tenant register specific logger.

your code could look like (extract from Autofac wiki)

    var tenantIdStrategy = new RequestParameterTenantIdentificationStrategy("tenant");
    var builder = new ContainerBuilder();
    builder.RegisterType<BaseDependency>().As<IDependency>();

    // If you have tenant-specific controllers in the same assembly as the
    // application, you should register controllers individually.
    builder.RegisterType<HomeController>();

    // Create the multitenant container and the tenant overrides.
    var mtc = new MultitenantContainer(tenantIdStrategy, builder.Build());
    mtc.ConfigureTenant("CompanyA",
       b =>
        {
          b.RegisterType<Tenant1Dependency>().As<IDependency>().InstancePerDependency();
          b.RegisterType<Tenant1Controller>().As<HomeController>();
        });

If this is the only instance where you need to differentiate the tenants and do not want to Ioc at this point you could create the factory like

static class LogFactory
{
    public static ILog GetLogger()
    {
        var requestUri = HttpContext.Current.Request.Url.AbsoluteUri;
        switch (requestUri)
        {
            case "companyA.domain.com":
                return LogManager.GetLogger("CompanyA");
            case "companyB.domain.com":
                return LogManager.GetLogger("CompanyB");
            default:
                return LogManager.GetLogger("default");
        }
    }
}

now use the factory instead of directly using Logmanager

 ILog logger = LogFactory.GetLogger();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!