Asp.Net核心Web应用程序中的SeriLog不会正确地注入依赖关系

时间:2018-06-16 04:38:54

标签: asp.net-core serilog

Startup.cs Configure()方法中,我设置了如下记录器:

        Serilog.Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Verbose()
            .Enrich.FromLogContext()
            .WriteTo.RollingFile(new CompactJsonFormatter(), "c:\\temp\\myapp.json")
            .CreateLogger();

        loggerFactory.AddSerilog(Serilog.Log.Logger);

ILogger和Log.Logger始终评估为Serilog.Core.Pipeline.SilentLogger而不是设置。我错过了设置DI的任何步骤吗?

2 个答案:

答案 0 :(得分:0)

在某些 Autofac 场景中可能会发生这种情况,其中调用builder.RegisterLogger();方法而不传递ILogger,但是由于任何原因 AutofacSerilogIntegration 无法检测先前创建的记录器。

如果您有一个ILogger实例,可以将其明确传递给容器构建器,如下所示:

builder.RegisterLogger(logger);

其中logger是ILogger的实现。

答案 1 :(得分:0)

要使我的工作正常,我必须调用AddProvider方法。

有点像这样:

        /* ok, need to get ILoggerFactory, i don't like this call to BuildServiceProvider, but that's what I had to do for my console-app (dotnetcore, not aspnetcore) */
        ILoggerFactory ilf = servColl.BuildServiceProvider().GetService<ILoggerFactory>();


        /* now create the SerilogLoggerProvider */
        Serilog.Extensions.Logging.SerilogLoggerProvider seriprovider = new Serilog.Extensions.Logging.SerilogLoggerProvider(serilogger, false);
        /* now cast the SerilogLoggerProvider to ILoggerProvider */
        Microsoft.Extensions.Logging.ILoggerProvider castSerilogger = seriprovider as Microsoft.Extensions.Logging.ILoggerProvider;

        /* now register the castSerilogger */
        ilf.AddProvider(castSerilogger);

上面是类似这样的不太平滑的版本:

https://andrewlock.net/adding-serilog-to-the-asp-net-core-generic-host/

https://github.com/serilog/serilog-extensions-hosting

如果上面的链接失败,这里有一些面包屑

"public class SerilogLoggerFactory : ILoggerFactory"

"_provider = new SerilogLoggerProvider(logger, dispose);"