【问题标题】:Change Minimum Level of Logging in SeriLog using appsettings.json使用 appsettings.json 更改 SeriLog 中的最低日志记录级别
【发布时间】:2021-10-28 21:01:54
【问题描述】:

有没有办法做到这一点? 我想通过读取 appsettings.json 的设置来更改最低日志记录级别

我的代码是这样的

            Serilog.Log.Logger = new LoggerConfiguration()
                .Enrich.WithExceptionDetails()
                .MinimumLevel.Verbose()
                .WriteTo.Console()
                .Enrich.WithProperty("Application", applicationName)
                .WriteTo.File(new JsonFormatter(renderMessage: true), "logs/myapp.txt", rollingInterval: RollingInterval.Day)
                .CreateLogger();

【问题讨论】:

  • 嗯,你试过什么?你读过文档吗?
  • 我知道如何从 appsettings.json 文件中读取值 - 但我不确定如何传入它,因为它不是枚举
  • 这应该有你需要的一切。 nblumhardt.com/2016/03/…
  • 向我们展示您的尝试:)
  • 我用这段代码获取了applicationName:

标签: c# serilog


【解决方案1】:

我能够通过使用 appsettings.json 定义 serilog 设置并使用代码添加 WriteTo 方法来完成此操作(我需要在代码中执行此操作,因为我将 renderMessage 参数传递给 JsonFormatter 的构造函数。

这是我的 appsettings.json 的样子:

  "Serilog": {
    "Using": [],
    "MinimumLevel": {
      "Default": "Verbose"
    },
    "Enrich": [ "WithExceptionDetails" ],
    "WriteTo": [
      {
        "Name": "Console"
      }
    ],
    "Properties": {
      "Application": "Sample Application"
    }
  },
  "LogsFilePath": "logs/myapp.txt",
  "LogsRollingInterval": "Day"

在我的代码中我这样做了:

            IConfigurationBuilder builder = new ConfigurationBuilder();
            builder.AddJsonFile(Path.Combine(Directory.GetCurrentDirectory(), "appsettings.json"));

            var config = builder.Build();

            Serilog.Log.Logger = new LoggerConfiguration()
                .ReadFrom.Configuration(config)
                .WriteTo.File(new JsonFormatter(renderMessage: true),
                    config.GetSection("LogsFilePath").Value,
                    rollingInterval: (RollingInterval)Enum.Parse(typeof(RollingInterval), config.GetSection("LogsRollingInterval").Value))
                .CreateLogger();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-02
    • 2014-09-01
    • 2023-04-11
    • 2019-07-08
    • 1970-01-01
    • 2016-02-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多