我试图用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
类中复制它时,_log
在Main(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
类?
答案 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>())