Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I configure logging in a Web Host mounted with Host.CreateDefaultBuilder

I am adapting the following WebHost.CreateDefaultBuilder method which works, into one based on Host.CreateDefaultBuilder So that I can use the UseWindowsService extension method.

// WORKING
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
  WebHost.CreateDefaultBuilder(args)
    .ConfigureLogging((hostingContext, logging) =>
    {
      ...
    })
    .UseStartup<Startup>();
}

When I try to adapt this...

public static IHostBuilder CreateHostBuilder(string[] args) =>
  Host.CreateDefaultBuilder(args)
    .UseWindowsService()
    .ConfigureLogging((hostingContext, logging) =>
    { // tried here
      ...
    })
    .ConfigureWebHostDefaults(webBuilder =>
    {
      webBuilder.ConfigureLogging((hostingContext, logging) =>
        { // tried here too
          ...
        });
        .UseStartup<Startup>();
    });

I get the following error...

Unable to resolve service for type 'Microsoft.Extensions.Logging.ILoggerFactory' while attempting to activate 'MyProject.Startup'.

What is the appropriate way to setup logging here?

like image 818
Tracker1 Avatar asked Oct 16 '25 13:10

Tracker1


1 Answers

Reference App startup in ASP.NET Core

Only the following service types can be injected into the Startup constructor when using the Generic Host (IHostBuilder):

  • IWebHostEnvironment
  • IHostEnvironment
  • IConfiguration

While your linked Startup appears to be injecting outside of the allowed services.

public Startup(ILoggerFactory loggerFactory)
{
  this._Factory = loggerFactory;
  this._Logger = loggerFactory.CreateLogger<Startup>();
}

Based on the linked Startup code, the logger does not appear to be used and the one reference to the logger is commented out, since based on the context of where it is used, it is not needed.

I would suggest removing the injection of the ILoggerFactory from Startup constructor as part of the refactoring to the newer version of the framework.

Everything else the original example code provide appears to be following the suggested format from the documentation and should work as expected.

like image 92
Nkosi Avatar answered Oct 18 '25 04:10

Nkosi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!