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

时间:2017-08-30 07:59:34

标签: c# asp.net-core serilog

来自@nblumhardtpost

  

然后你可以继续删除任何其他记录器配置: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提供一些信息?

据我所知,

我的课程课程遵循帖子中的说明。

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 个答案:

答案 0 :(得分:5)

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

private readonly ILogger _logger;

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

答案 1 :(得分:3)

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

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

答案 2 :(得分:-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");
    }