【问题标题】:Serilog With API App in AzureAzure 中带有 API 应用程序的 Serilog
【发布时间】:2018-03-19 15:53:22
【问题描述】:

我已将 Serilog 集成到使用 Asp.Net Core 2.0 开发的 WebApi 项目中 这是Program.cs中的配置代码:

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

我在调试过程中完美地看到了日志。
现在我在 Azure 中将服务部署为 API 应用程序。
通过 Azure Portal 中的 Log Stream 扩展查看生产环境中的日志应该应用什么配置?

【问题讨论】:

  • 你试过.WriteTo.Trace()吗?这应该写入日志流,因为它显示了写入跟踪的内容。

标签: c# azure asp.net-web-api serilog azure-api-apps


【解决方案1】:

据我所知,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 路径中找到它:


更新:

如果您想使用 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");

并启用诊断日志。

然后打开日志流并找到应用程序日志。

您会发现日志已经登录到日志蒸汽中。

文件夹:

【讨论】:

  • 您的解决方案当然会奏效。但是,(对我来说)如何在 Azure 中通过 Serilog 使用 Log Streaming 功能仍然不清楚
  • 据我所知,如果您想在 Azure 中使用日志流功能,您只能在 Web 应用中启用“诊断日志”。
  • 更新:如果您想使用 Serilog 将日志记录到 azure 日志流中,您需要首先在 Web 应用中启用“诊断日志”。然后,您可以使用 Serilog 将文件记录到 azure 默认的“诊断日志”文件夹。例如:D:\home\LogFiles\http\RawLogs。然后日志将显示在日志流中。更多细节,你可以看到我的更新答案。
  • 我也有类似的要求。我想知道当由于网络问题导致与云的连接失败时,我们如何管理日志?它会登录到本地本地服务器并在连接建立后发送吗?第二个问题是,审计日志也可以使用 serilog 发送到云端吗?审计日志必须要有数据库吗?
  • RollingFile 现已弃用,请更新您的答案。
猜你喜欢
  • 2015-07-15
  • 2018-10-11
  • 1970-01-01
  • 2022-10-17
  • 1970-01-01
  • 2013-07-31
  • 2017-07-14
  • 2014-01-12
  • 2017-03-29
相关资源
最近更新 更多