dotnet logging serilog support

add serilog packages

dotnet add package serilog.aspnetcore
dotnet add package Serilog.Sinks.Console

add serilog support

using Serilog;
using Serilog.Formatting.Json;

  ServiceCollection services = new ServiceCollection();

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

  services.AddLogging(logBuilder => {
      // logBuilder.AddNLog();  // add nlog support
      logBuilder.AddSerilog();
  });

  // test with Serilog
  int itemNumber = 123, itemCount = 222;
  Log.Debug("Processing item {ItemNumber} of {ItemCount}", itemNumber, itemCount);

use dotnet core ILogger

class TestController
{
    // IOptions: 
    // IOptionsSnapshot: 
    // IOptionsMonitor: 
    private IOptionsSnapshot<Config> optConfig { get; }
    private ILogger<TestController> logger { get; }

    public TestController(IOptionsSnapshot<Config> config, ILogger<TestController> logger)
    {
        optConfig = config;
        this.logger = logger;
    }

    public void Test()
    {
        logger.LogInformation("enter Test");
        logger.LogDebug("can you see me?");
        System.Console.WriteLine(optConfig.Value);
        logger.LogInformation("leave  Test");
    }
}

structured log output

{"Timestamp":"2022-01-17T21:05:01.8240220+11:00","Level":"Debug","MessageTemplate":"Processing item {ItemNumber} of {ItemCount}","Properties":{"ItemNumber":123,"ItemCount":222}}
{"Timestamp":"2022-01-17T21:05:01.9875653+11:00","Level":"Information","MessageTemplate":"enter Test","Properties":{"SourceContext":"consoleApp01.Controllers.TestController"}}
{"Timestamp":"2022-01-17T21:05:01.9909203+11:00","Level":"Debug","MessageTemplate":"can you see me?","Properties":{"SourceContext":"consoleApp01.Controllers.TestController"}}
name:, age:0, proxy:
{"Timestamp":"2022-01-17T21:05:02.0006510+11:00","Level":"Information","MessageTemplate":"leave  Test","Properties":{"SourceContext":"consoleApp01.Controllers.TestController"}}
上一篇:npm WARN npm npm does not support Node.js v14.16.0 npm WARN npm You should probably upgrade to a new


下一篇:Bootstrap后台管理模板调研