Serilog 是如何检索关键信息的?

How does Serilog retrieve key information?

我需要这样的需求,我需要使用日志框架创建任何类型的日志消息记录。然后在一些关键的地方记录一些日志,然后我需要从中提取一些信息,这是怎么做到的?

enter image description here

像这样,或者有没有其他更容易实现的框架?非常感谢任何帮助。

所需的 Nuget 包:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Serilog.AspNetCore" Version="4.1.0" />
    <PackageReference Include="Serilog.Settings.Configuration" Version="3.3.0" />
    <PackageReference Include="Serilog.Sinks.Console" Version="4.0.1" />
    <PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
  </ItemGroup>

  <ItemGroup>
    <Folder Include="MyLogInfo\" />
  </ItemGroup>

</Project>

appsettings.json 配置:

{

  "Serilog": {
    "MinimumLevel": "Information",
    "Override": {
      "Microsoft.AspNetCore": "Warning"
    },
    "WriteTo": [
      {
        "Name": "Console "
      },
      {
        "Name": "File",
        "Args": {
          "path": "MyLogInfo\MyLogInfo.txt",
          "formatter": "Serilog.Formatting.Json.JsonFormatter, Serilog"
        }
      }
    ]
  }
}

然后在startup.cs中添加代码,在构造函数中读取这些Serilog设置:

 public Startup(IConfiguration configuration)
        {
            Configuration = configuration;

            Log.Logger = new LoggerConfiguration()
       .ReadFrom.Configuration(configuration)
       .CreateLogger();
        }

最后更改program.cs中的代码以指定Host Builder使用来自ASP.NET Core的Serilog而不是默认记录器:

 public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
            .UseSerilog()
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }

结果:

更多详情请参考这篇文章:

Implementing logging with Serilog

更多日志框架可以看这篇:

Logging in .NET Core and ASP.NET Core

那么你想从这个日志中读取信息吗?

你可以阅读这篇文章:

https://docs.microsoft.com/en-us/previous-versions/windows/apps/hh758325(v=win.10)