1

我正在使用下面的代码来访问非基于主机的控制台应用程序的 Serilog。我有两个要求要实现。

初始化 Serilog 后,我应该能够在所有其他类中访问 MS 扩展 Logger。我们应该能够在执行每个日志记录行后看到日志记录语句。我正在使用下面的代码。

程序.cs

private static void main()
    {
        var configuration = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json")
            .Build();

        Log.Logger = new LoggerConfiguration()
            .ReadFrom.Configuration(configuration)
            .CreateLogger();

        Log.Logger.Information("hello");  //it's not printing the hello in console window.
    }

应用设置.json

    "Serilog": {
    "MinimumLevel": "Verbose",
    "WriteTo": [
        {
            "Name": "Async",
            "Args": {
                "configure": [
                    {
                        "Name": "Console",
                        "Args": {
                            "theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Code, Serilog.Sinks.Console",
                            "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:j}{NewLine}{Properties:j}{NewLine}{Exception}"
                        }
                    },
                    {
                        "Name": "File",
                        "Args": {
                            "restrictedToMinimumLevel": "Warning",
                            "path": "Logs\\log.txt",
                            "rollingInterval": "Day",
                            "fileSizeLimitBytes": 10240,
                            "rollOnFileSizeLimit": true,
                            "retainedFileCountLimit": 30
                        }
                    }
                ]
            }
        }
    ],
    "Enrich": [ "FromLogContext", "WithMachineName", "WithExceptionDetails" ],
    "Properties": {
        "ApplicationName": "SampleApp",
        "Environment": "Int"
    }
}

}```

4

1 回答 1

0

你的配置没问题。

您的代码错过了Log.CloseAndFlush();
查看文档的调用。

您的代码应如下所示。

private static void main()
{
    var configuration = new ConfigurationBuilder()
        .AddJsonFile("appsettings.json")
        .Build();

    Log.Logger = new LoggerConfiguration()
        .ReadFrom.Configuration(configuration)
        .CreateLogger();

    Log.Logger.Information("hello");
    
    Log.CloseAndFlush();
}
于 2022-03-01T22:48:43.997 回答