asp.net 核心 - 从 appsettings.json 设置 Serilog.Exceptions

asp.net core - Set Serilog.Exceptions from appsettings.json

我需要使用 Serilog.Exceptions 包来捕获异常。 从 appsettings.json

读取 Serilog
{
    "Serilog": {
        "Using": [
            "Serilog.Sinks.RollingFile",
            "Serilog.Sinks.Seq"
        ],
        "WriteTo": [
            {
                "Name": "RollingFile",
                "Args": {
                    "restrictedToMinimumLevel": "Debug",
                    "pathFormat": "myPath\log-{Date}.log"
                }
            },
            {
                "Name": "RollingFile",
                "Args": {
                    "restrictedToMinimumLevel": "Error",
                    "pathFormat": "myPath\error-{Date}.log"
                }
            },
            {
                "Name": "Seq",
                "Args": {
                    "serverUrl": "myUrl",
                    "apiKey": "myApiKey"
                }
            }
        ],
        "Enrich": [
            "FromLogContext",
            "WithMachineName",
            "WithThreadId"
        ],
        "Properties": {
            "Application": "myApplicationName"
        }
    }
}

而在我的 startup.cs

var logger = new LoggerConfiguration()
    .Enrich.WithExceptionDetails()
    .ReadFrom.Configuration(Configuration)
    .CreateLogger();

Log.Logger = logger;

但是没用。我是否需要在 appsettings.json 中为 Serilog.Exceptions 包添加一些其他属性?还是 appsettings.json 配置正确?我究竟做错了什么? 谢谢

以下是我在 ASP.NET Core 2.1 中设置 Serilog 的方法。你可以把它当作清单,看看你错过了什么。

  1. 从 Nuget 安装包:Serilog.AspNetCoreSerilog.ExceptionsSerilog.Settings.Configuration 和您要使用的其他接收器。
  2. 在您的主程序中设置 Serilog

    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }
    
        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .UseSerilog((hostingContext, loggerConfiguration) => 
                    loggerConfiguration
                        .ReadFrom.Configuration(hostingContext.Configuration)
                );
    }
    
  3. WithExceptionDetails 放入 appsettings.json 中的 Serilog 部分:

    {
        "Serilog": {
            ...
            "Enrich": [
                "FromLogContext",
                "WithExceptionDetails"
            ],
            ...
        }
    }