I have an asp.net core 2.2 solution. The structure looks like MyProject MyProject.Web
everything is inside MyProject project and I just keep web for declarations.
I have added the Microsoft.Extensions.Logging.Log4Net.AspNetCore
reference to MyProject.Web I have added loggerFactory.AddLog4Net();
in the Startup.cs. I have also added log4net.config in the MyProject.Web and set to Always Copy
. I have a service in MyProject project call ServiceA
public class ServiceA
{
private readonly ILogger logger;
public ServiceA(ILogger logger)
{
this.logger = logger;
}
}
However when I run the solution it crashes with error HTTP Error 500.30 - ANCM In-Process Start Failure
. When I remove ILogger from constructor of ServiceA the project runs. Anything else I am missing here?
You should inject a strongly-typed logger instead :
public class ServiceA
{
private readonly ILogger logger;
public ServiceA(ILogger<ServiceA> logger)
{
this.logger = logger;
}
}
This is the simple scenario shown in the documentation too . The docs show that the target type is used as the category name for the logger :
Get an ILogger object from DI.
Using a controller's type name as
I've made the same mistake from time to time, but I can't remember what the exception is. If I remember correctly, it's that the DI container can't find an ILogger instance. Which makes sense, since the extensions register a strongly typed logger . The source code for AddLogging
contains this line:
services.TryAdd(ServiceDescriptor.Singleton(typeof(ILogger<>), typeof(Logger<>)));
As the ILogger< TCategoryName> docs explain, this is used to create named loggers based on a type name instead of a string:
A generic interface for logging where the category name is derived from the specified TCategoryName type name. Generally used to enable activation of a named ILogger from dependency injection.)
You need to inject like this
public class HomeController : Controller
{
private readonly IQueueService _queueService;
private readonly ILogger<HomeController> _logger;
public HomeController(
IQueueService queueService,
ILogger<HomeController> logger)
{
_queueService = queueService;
_logger = logger;
}
[HttpGet]
public IActionResult Index()
{
return View();
}
}
Please let me know if you still have problem
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.