其他分享
首页 > 其他分享> > dotnet logging serilog support

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"}}

标签:MessageTemplate,serilog,support,TestController,Test,add,dotnet,logger,Debug
来源: https://www.cnblogs.com/mryux/p/15814640.html