据我所知,Serilog.Sinks.Console 会将日志事件写入 Windows 控制台。但如果将应用程序发布到azure,我们将无法直接看到控制台。
我建议你可以考虑使用Serilog.Sinks.RollingFile https://github.com/serilog/serilog-sinks-rollingfile or Serilog.Sinks.ApplicationInsights https://github.com/serilog/serilog-sinks-applicationinsights#serilogsinksapplicationinsights而不是控制台来写入日志事件。
关于如何使用Serilog.Sinks.RollingFile或Serilog.Sinks.ApplicationInsights,您可以参考以下代码。
首先,安装Serilog.AspNetCore https://www.nuget.org/packages/Serilog.AspNetCore and Serilog.Sinks.RollingFile https://www.nuget.org/packages/Serilog.Sinks.RollingFile/来自 Nuget 的包。
然后您可以使用下面的代码来记录信息。
//if you want to use ApplicationInsights just change the write to's method as Serilog.Sinks.ApplicationInsights links shows
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.Enrich.FromLogContext()
.WriteTo.RollingFile("log-{Date}.txt")
.CreateLogger();
Log.Information("This will be written to the rolling file set");
它将自动创建 txt 文件来记录事件。
结果是这样的,你会在应用程序的 wwwroot 路径中找到它:
Update:
如果您想使用 Serilog 将日志记录到 azure 日志流,您需要首先在 Web 应用程序中启用“诊断日志”。然后,您可以使用 Serilog 将文件记录到天蓝色默认的“诊断日志”文件夹。例如:D:\home\LogFiles\http\RawLogs。然后日志将显示在日志流中。
使用下面的代码进行测试:
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.Enrich.FromLogContext()
.WriteTo.File(@"D:\home\LogFiles\http\RawLogs\log.txt")
.CreateLogger();
Log.Information("This will be written to the rolling file set");
并启用诊断日志。
然后打开日志流并找到应用程序日志。
可以发现日志已经登录到log-steam中了。
文件夹: