Serilog在.NET Core 2.1中无法记录到控制台

3
我创建了一个新的ASP.NET Core 2.1 Web应用程序,并添加了这些Nuget包:
Serilog.AspNetCore 2.1.1
Serilog.Settings.Configuration 2.6.1
Serilog.Sinks.Console 3.1.1

Program.cs看起来像这样:

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)
                .Enrich.FromLogContext()
                .WriteTo.Console());
}

这是 appsettings.json 文件:

{
  "Serilog": {
    "Using": [ "Serilog.Sinks.Console" ],
    "MinimumLevel": "Debug",
    "WriteTo": [
      { "Name": "Console" }
    ],
    "Enrich": [ "FromLogContext" ],
    "Properties": {
      "Application": "MyApplication"
    }
  }
}

我添加了一个控制器,代码如下:

public class HelloController : Controller
{
    // GET
    public IActionResult Index()
    {
        Log.Debug("Test");
        return new OkObjectResult("Hello world");
    }
}

虽然HelloController本身按预期工作,但我没有在控制台上看到Test的调试输出。
这是调用控制器后的控制台日志输出:
[21:39:16 DBG] Connection id "0HLEJO3CE6S7J" started.
[21:39:16 DBG] Connection id "0HLEJO3CE6S7J" started.
[21:39:16 INF] Request starting HTTP/1.1 GET http://localhost:5000/api/hello
[21:39:16 INF] Request starting HTTP/1.1 GET http://localhost:5000/api/hello
[21:39:17 DBG] Connection id "0HLEJO3CE6S7J" completed keep alive response.
[21:39:17 DBG] Connection id "0HLEJO3CE6S7J" completed keep alive response.
[21:39:17 INF] Request finished in 80.8969ms 200
[21:39:17 INF] Request finished in 80.8969ms 200
[21:39:17 DBG] Connection id "0HLEJO3CE6S7J" received FIN.
[21:39:17 DBG] Connection id "0HLEJO3CE6S7J" received FIN.
[21:39:17 DBG] Connection id "0HLEJO3CE6S7J" disconnecting.
[21:39:17 DBG] Connection id "0HLEJO3CE6S7J" disconnecting.
[21:39:17 DBG] Connection id "0HLEJO3CE6S7J" sending FIN.
[21:39:17 DBG] Connection id "0HLEJO3CE6S7J" sending FIN.
[21:39:17 DBG] Connection id "0HLEJO3CE6S7J" stopped.
[21:39:17 DBG] Connection id "0HLEJO3CE6S7J" stopped.
2个回答

0

找到了:

不是我的控制器返回了“Hello world”,而是在Startup.cs中的这一行:

app.Run(async (context) => { await context.Response.WriteAsync("Hello World!"); });

你能在调试中看到Serilog日志吗?(不添加sink) - Green

0

我建议进行一些改进:

  1. 不要重复配置接收器,没有必要在代码和appsettings中同时配置相同的接收器。选择一个并使用它。
  2. ASP .NET Core支持依赖注入。在HelloController中注入ILogger<HelloController>,而不是访问静态的Log.Debug
  3. 感谢您在问题中找到并报告了该问题,这肯定会帮助其他开发人员。

关于Serilog和ASP .NET Core 2.1的一个非常小的示例,请查看此repo


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接