在核心 2 日志记录更新后将 ILogger 映射到 Serilog ASP.NET 记录器



来自@nblumhardt的帖子:

然后,您可以继续删除任何其他挂起的记录器配置:在appsettings.json中不需要"Logging"部分,在任何位置都不需要AddLogging((,也不需要通过Startup.cs中的ILoggerFactory进行配置。

控制器中的using Serilog;ILogger出现异常。

private readonly ILogger _logger;
public CustomersController(ILogger logger)
{
_logger = logger;
}

结果:

处理请求时发生未处理的异常
InvalidOperationException:在尝试激活"Customers.Api.Controllers.CustomersController"时,无法解析类型为"Serilogr.ILogger"的服务。

我还需要在Startup.ConfigureServices()方法中向DI提供一些信息吗?

据我所知,我的程序课遵循了帖子中的说明。

public class Program
{
public static void Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.Enrich.FromLogContext()
.WriteTo.Console()
.CreateLogger();
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseSerilog()
.Build();
}

将预期类型从ILogger logger更改为ILogger<CustomersController>记录器:

private readonly ILogger _logger;
public CustomersController(ILogger<CustomersController> logger)
{
_logger = logger;
}

如果您仍然希望使用Serilog自己的ILogger而不是ASP.NET Core的ILogger<T>,另一种选择是在IoC容器中注册Serilog记录器。

Autofac在https://github.com/nblumhardt/autofac-serilog-integration,其他容器可能也有集成包。

您可以按照以下代码进行操作。

//using Microsoft.Extensions.Logging;
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseMvc();
//Logger for File
loggerFactory.AddFile("FilePath/FileName-{Date}.txt");
}
}
//Add following code into Controller:
private readonly ILogger<ControllerName> _log;
public ControllerConstructor(ILogger<ControllerName>logger)
{
_log = logger;
}
[HttpGet]
public ActionResult GetExample()
{
try
{
//TODO:Log Informationenter code here
_log.LogInformatio("LogInformation");
}
catch (Exception exception)
{
//TODO: Log Exception
_log.LogError(exception, exception.Message + "nn");
} 
return view("viewName");
}

最新更新