Search code examples
asp.net-coreserilog

How does Serilog retrieve key information?


I need a requirement like this, I need to create a log message record of any kind using the logging framework. Then record some logs in some key places, and then I need to retrieve some information from it, how is this done?

enter image description here

Like this, or is there any other framework that is easier to implement? Any help is greatly appreciated.


Solution

  • Required Nuget Packages:

    <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 configuration:

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

    Then add code in startup.cs to read these Serilog settings in the constructor:

     public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
    
                Log.Logger = new LoggerConfiguration()
           .ReadFrom.Configuration(configuration)
           .CreateLogger();
            }
    

    Finally change the code in program.cs to specify that Host Builder uses Serilog from ASP.NET Core instead of the default logger:

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

    Result:

    enter image description here

    enter image description here

    For more details, please refer to this article:

    Implementing logging with Serilog

    More logging frameworks can read this:

    Logging in .NET Core and ASP.NET Core

    Then you want to read information from this log?

    You can read this article:

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