在ASP.NET Core 2日志更新后,将ILogger映射到Serilog的Logger

8

以下是从@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”时无法解析类型“Serilog.ILogger”的服务。

我是否仍需要在Startup.ConfigureServices()方法中提供一些信息给DI?

据我所知,我的Program类按照帖子中的说明进行了操作。

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();
}
3个回答

8

将期望的类型从ILogger logger更改为ILogger<CustomersController> logger:

private readonly ILogger _logger;

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

谢谢。我重置了我的编辑以进行测试,它起作用了。我们知道为什么吗? :-) - leon

3
如果您仍然希望使用 Serilog 自己的 ILogger 而不是 ASP.NET Core 的 ILogger<T>,另一种选择是将 Serilog 记录器注册到您的 IoC 容器中。
Autofac 有一个集成插件可以完成这个任务,可以在 https://github.com/nblumhardt/autofac-serilog-integration 找到,其他容器可能也有相应的集成包。

-3

您可以按照以下代码进行使用。

//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 + "\n\n");
        } 
        return view("viewName");
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接