在Azure中使用API应用程序的Serilog

15

我已经将Serilog整合到使用Asp.Net Core 2.0开发的WebApi项目中。

这是在Program.cs中的配置代码:

Log.Logger = new LoggerConfiguration()
        .Enrich.FromLogContext()
        .WriteTo.Console()
        .CreateLogger();

我在调试期间成功地查看了日志。
现在我将服务部署为 Azure API 应用程序。
在 Azure 门户中使用日志流扩展程序,应该应用什么配置才能在生产环境中查看日志?


你尝试过使用.WriteTo.Trace()吗?这应该会将日志写入流中,因为它显示了已写入的跟踪内容。 - Siva Kandaraj
1个回答

18
据我所知,Serilog.Sinks.Console会将日志事件写入Windows控制台。但是,如果您将应用程序发布到Azure,则无法直接看到控制台。
我建议您考虑使用Serilog.Sinks.RollingFileSerilog.Sinks.ApplicationInsights而不是控制台来写入日志事件。
关于如何使用Serilog.Sinks.RollingFile或Serilog.Sinks.ApplicationInsights,您可以参考下面的代码。
首先,从Nuget安装Serilog.AspNetCoreSerilog.Sinks.RollingFile包。
然后,您可以使用以下代码记录信息。
    //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文件来记录事件。
结果如下,在应用程序wwwrot路径中可以找到:

enter image description here


更新:

如果您想使用Serilog将日志记录到Azure日志流中,您首先需要在Web应用程序中启用“诊断日志”。之后,您可以使用Serilog将文件记录到Azure默认的“诊断日志”文件夹。例如: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");

并启用诊断日志。

enter image description here

然后打开日志流并定位应用程序日志。

您可以发现日志已经记录到日志流中。

enter image description here

文件夹:

enter image description here


您的解决方案当然可行。然而,对于我来说,如何使用Serilog在Azure中的日志流传输功能仍不清楚。 - ZENIT
据我所知,如果您想在Azure中使用日志流功能,您只能在Web应用程序中启用“诊断日志”。 - Brando Zhang
2
{btsdaf} - Brando Zhang
我有类似的需求。我想知道当由于网络问题连接到云端失败时,我们如何管理日志?它会被记录在本地的本地服务器上,并在连接恢复后发送吗?第二个问题是,审计日志是否也可以使用Serilog发送到云端?审计日志必须要有数据库吗? - kudlatiger
1
RollingFile 现已弃用,请更新您的答案。 - Ahmad Hamdy
你的应用程序文件夹在哪里找到的?如果我是说不是本地的话?我在Azure上找不到它们。 - m3.b

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接