Reputation: 13
I have a project implementing .Net Core hosting pattern.
So I have a host builder:
public static async Task Main(string[] args)
{
var builder = new HostBuilder()
.ConfigureAppConfiguration((hostingContext, config) =>
{
...
})
.ConfigureServices((hostContext, services) =>
{
services.AddSingleton<IHostedService, SkillsService>();
})
.ConfigureLogging((hostingContext, logging) =>
{
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
logging.AddConsole();
});
await builder.RunConsoleAsync();
}
and a service:
public class SkillsService : IHostedService, IDisposable
{
...
public SkillsService(ILogger<SkillsService> logger)
{
...
}
public async Task StartAsync(CancellationToken cancellationToken)
{
...
}
public Task StopAsync(CancellationToken cancellationToken)
{
...
}
public void Dispose()
{
...
}
}
Now, in the StartAsync method, I want to create an instance of a class from my own library and that class is also implementing the ILogger interface. So I need to create a new instance of the Logger with the configuration from the IHostBuilder, but with the category matching the full namespace name of that library, and inject such logger to the class. I've found a lot about creating new LoggerFactory instance and configuring it, but I want to reuse the one already set up by the HostBuilder. How should I do that? There is no LoggerFactory inside the IHostedService.
For logging, I am using Microsoft.Extensions.Logging namespace.
Thanks for any bits of advice.
George
Upvotes: 0
Views: 1244
Reputation: 339
To the best of my knowledge, I had to install some nuggets to enhance Microsoft.Extensions.Logging
and if you want to store the log into a file
Let me know if this tip, solve your problem.
Regards.
Upvotes: -2