程序类中的Serilog

时间:2018-12-23 14:58:58

标签: c# logging asp.net-core serilog

我试图用Serilog登录ASP.NET Core应用程序的Program.cs类。我当前的设置如下:

public class Program
{
    public static void Main(string[] args)
    {
        DoStuff();
        CreateWebHostBuilder(args).Build().Run();
    }
    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .ConfigureLogging((hostingContext, builder) =>
            {
                builder.AddFile(@"C:\...\log-{Date}.txt", isJson: true);
            })
            .UseStartup<Startup>();
}

我可以通过以下操作成功登录Controller类:

public class WebhookController : Controller
{
    readonly ILogger<WebhookController> _log;
    public WebhookController(ILogger<WebhookController> log)
    {
        _log = log;
    }
    public IActionResult Index()
    {
        _log.LogInformation("hello world");
        return View();
    }
}

但是,当尝试在program类中复制它时,_logMain(string[] args)中不可访问:

public class Program
{
    readonly ILogger<Program> _log;
    public Program(ILogger<Program> log)
    {
        _log = log;
    }

    public static void Main(string[] args)
    {
        DoStuff();
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .ConfigureLogging((hostingContext, builder) =>
            {
                builder.AddFile(@"C:\...\log-{Date}.txt", isJson: true);
            })
            .UseStartup<Startup>();
}

如何配置Serilog登录program类?

2 个答案:

答案 0 :(得分:2)

构建Web主机后,IWebHost会公开IWebHost.Services Property

public IServiceProvider Services { get; }

可用于解决所需的依赖性。

public class Program {

    public static void Main(string[] args) {
        var webHost = CreateWebHostBuilder(args).Build();
        var services = webHost.Services;

        var log = services.GetService<ILogger<Program>>();

        DoStuff(log);

        webHost.Run();
    }

    static void DoStuff(ILogger<Program> log) {
        //...
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .ConfigureLogging((hostingContext, builder) =>
            {
                builder.AddFile(@"C:\...\log-{Date}.txt", isJson: true);
            })
            .UseStartup<Startup>();
}

请记住包括using Microsoft.Extensions.DependencyInjection;,以便可以访问.GetService<T>()上的IServiceProvider扩展方法。

答案 1 :(得分:0)

尝试将Program添加到您的服务中。 像这样的东西:

.Configure(services => services.AddTransiant<Program>())