Reputation: 403
Recently I have been working on a project based on a template written by another group in my company. This project built with asp.net core 2.2
and it uses NLog
as a logging framework behind the ILogger
registered in the ILoggerFactory
.
I noticed an interesting point that any service depend on ILogger<service> logger
gets a new instance of the logger
. The service indeed is registered as transient
so its creation per request seems normal, but as I read here I expect that the logger
will be the same (i.e. singelton
) instance for all instances of this service.
I can't upload all the code seems it's big and private. But it seems that the relevant lines are those:
public static IWebHostBuilder CreateBuildWebHost(string[] args)
{
return WebHost.CreateDefaultBuilder<Startup>(args).UseUnityServiceProvider()
.ConfigureAppConfiguration((hostingContext, configurationBuilder) =>
{
//...
})
.ConfigureLogging((hostingContext, logging) =>
{
logging.ClearProviders();
logging.SetMinimumLevel(LogLevel.Information);
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
LoadExternalNLogConfigFile(hostingContext);
})
.UseNLog(); // NLog: setup NLog for Dependency injection
}
And those:
private static void LoadExternalNLogConfigFile(WebHostBuilderContext hostingContext)
{
var isRunningInContainer = hostingContext.Configuration.GetValue<bool>("DOTNET_RUNNING_IN_CONTAINER");
var xmlNLogConfigFilenameWithEnvName =
$"nlog.{(isRunningInContainer ? "Docker." : "")}{hostingContext.HostingEnvironment.EnvironmentName}.config";
var xmlNLogConfigFilename = $"nlog.{(isRunningInContainer ? "Docker." : "")}config";
try
{
hostingContext.HostingEnvironment.ConfigureNLog(xmlNLogConfigFilenameWithEnvName);
}
catch
{
hostingContext.HostingEnvironment.ConfigureNLog(xmlNLogConfigFilename);
}
}
In order to check the equality of the logger
instance, I've used the solutions described here.
I've tested also the Nlog
"Hello world" project, as guided here. The test shown that the logger instance is identical for each request.
My question: Do creation of a new ILogger
instance per object request costs expensive? Should I have to look for solution for that issue, or is it a negligible problem?
Upvotes: 1
Views: 2624
Reputation: 7702
The quick answer is yes: it would be expensive.
However, there would be no reason to do that. Any logging system will create loggers as singletons in the IoC container or recycle loggers for the category in the ILoggerFactory
implementation. The main point is that this is not something you should worry about. Just configure your logging on startup, and then inject ILogger<YourController>
into controllers and other services. The logging infrastructure will manage reuse of the logger for you with DI magic.
Upvotes: 1