我在下面代码中的目标是创建一个根异常处理程序,它将处理所有其他未处理的错误。当我在 Azure 上的 IIS 下运行我的 Web 应用程序时,它立即崩溃。日志文件如下所示。 当我在命令行运行程序时,我可以看到错误。
我的问题是:
为什么没有记录错误?
如何编写处理程序以便记录所有错误?
程序.cs
public class Program
{
public static void Main(string[] args)
{
string env = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
string logRoot = null;
if (env == "Development")
logRoot = "c:\\serilog\\myDomain.Web\\log";
else
logRoot = "..\\..\\serilog\\myDomain.Web\\log"; // Create logs in D:\home\serilog
Log.Logger = new LoggerConfiguration()
.WriteTo.File(logRoot, rollingInterval: RollingInterval.Day, restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Information)
.CreateLogger();
try
{
Log.Information("myDomain.Web - Program.Main started.");
Log.Information("Environment is: {env}", env);
CreateHostBuilder(args).Build().Run();
}
catch (Exception ex)
{
Log.Error(ex.ToString());
}
finally
{
Log.CloseAndFlush();
}
}
2021-01-07 15:58:44.833 +00:00 [INF] myDomain.Web - Program.Main 已启动。
<块引用>2021-01-07 15:58:45.009 +00:00 [INF] 环境为:空
D:\home\site\wwwroot>myDomain.Web.exe
暴击:Microsoft.AspNetCore.Hosting.Diagnostics[6]
应用程序启动异常
System.IO.DirectoryNotFoundException: D:\home\site\wwwroot\StaticHTML
在 Microsoft.Extensions.FileProviders.PhysicalFileProvider..ctor(String root, ExclusionFilters 过滤器)
在 Microsoft.Extensions.FileProviders.PhysicalFileProvider..ctor(String root)
在 LeaderAnalytics.myDomain.Web.Startup.Configure(IApplicationBuilder app, IWebHostEnvironment env) 在 D:\a\1\s\myDomain.Web\Startup.cs:line 57
在 System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
显示的异常处理程序是根异常处理程序。为了证明它应该处理我引用的特定异常,我用 throw statement
替换了我的代码(因为我的代码在 dev 中工作但在 prod 中失败)并观察到如下图所示的处理程序被调用。
throw new Exception("boo");
app.UseStaticFiles(new StaticFileOptions // this line fails in prod
答案 0 :(得分:0)
感谢 Nicholas 上面的评论,我终于明白了。
https://nblumhardt.com/2019/10/serilog-in-aspnetcore-3/
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseSerilog() // <- Add this line
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
答案 1 :(得分:0)
看起来没问题。但是您是否在 startup.cs 的 configureservice 方法中添加了日志的依赖项(DI)或相关的日志框架类?
像这样:public void ConfigureServices(IServiceCollection services) { services.AddSingleton<ILogger, Logger>(); }