无法在dotnet core 2.1中注册日志记录

我创建了一个新的dotnet核心项目,该项目发布:


dotnet new mvc -au none -o aspnet_app

然后按照本指南向应用程序添加日志记录


所以我将COnfigureLogging添加到Program.BuildWebHost


public static IWebHost BuildWebHost(string[] args) =>

    WebHost.CreateDefaultBuilder(args)

        .ConfigureLogging((hostContext, logging) => 

        {

            logging.AddConfiguration(hostContext.Configuration.GetSection("Logging"));

            logging.AddConsole();

        })

        .UseStartup<Startup>()

        .Build();

并且还修改了Startup.cs


public void ConfigureServices(IServiceCollection services)

{

    services.AddLogging();

    services.AddMvc();

}

但是当我在HomeController中尝试使用它时:


private readonly ILogger<HomeController> _logger;

public HomeController(ILogger<HomeController> logger) {

    _logger = logger;

}

public IActionResult Index()

{

    _logger.LogInformation("Index action!");

    return View();

}

我收到以下错误:


fail: Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[0]

  An unhandled exception has occurred: Unable to resolve service for type 'Microsoft.Extensions.Logging.ILogger' while attempting to activate 'aspnet_app.Controllers.HomeController'.

--


使用dotnet core 2.1.105


侃侃无极
浏览 127回答 1
1回答

智慧大石

您正在对它进行编码。 CreateDefaultBuilder生成自动获取hostContext.Configuration.GetSection(“ Logging”)的记录器, 您实际上不需要在program.cs或启动中添加注释。只需编辑基本项目并添加它,它将起作用。public HomeController(ILogger<HomeController> logger)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; _logger = logger;&nbsp; &nbsp; }&nbsp; &nbsp; public IActionResult Index()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; _logger.LogInformation("Index action!");&nbsp; &nbsp; &nbsp; &nbsp; return View();&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP