How do I log from other classes than the controller in ASP.NET Core?

后端 未结 3 1709
悲&欢浪女
悲&欢浪女 2021-02-04 03:34

ASP.NET Core has built-in support for logging, but the documentation states that logging should be done by requesting an ILogger via dependency injection, i.e. by a

3条回答
  •  时光取名叫无心
    2021-02-04 03:43

    Sharing Bjorn Reppens concerns regarding the accepted answer, and taking Cyprien Autexiers comments into account, I ended up with this (boiled down) solution for "built in DI" without "polluting constructors" in "other classes than the controller" in .NET Core 3.1

    Factory:

    public class Runtime
    {
        public static ILogger GetLogger()
        {
            using var serviceScope = host.Services.CreateScope();
            var services = serviceScope.ServiceProvider;
            return services.GetRequiredService>();
        }
    
        static IHost host;
    
        CancellationTokenSource CancellationSource { get; } = new CancellationTokenSource();
    
        Task hostTask;
    
        public void Start()
        {
            var hostBuilder = Host.CreateDefaultBuilder();
            hostBuilder.ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup());
            host = hostBuilder.Build();
            hostTask = host.RunAsync(CancellationSource.Token);
        }
    }
    

    Client:

    public class OtherClass
    {
        ILogger Logger { get; }
    
        public OtherClass() => Logger = Runtime.GetLogger();
    }
    

    For further abstraction:

    public abstract class LoggerBase
    {   
        protected ILogger Logger { get; }
    
        protected LoggerBase() => Logger = RunTime.GetLogger();
    }
    

    e.g.

    public class OtherClass : LoggerBase
    {
        public OtherClass() => Logger.LogInformation("Instantiated");
    }
    

提交回复
热议问题