Serilog不会在.NET Core 2.1中登录到控制台

时间:2018-06-16 19:44:20

标签: asp.net-core serilog

我创建了一个新的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 Debug输出。

这是调用Controller后的控制台日志输出:

[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 :(得分:0)

找到它:

这不是我的控制器返回&#34; Hello world&#34;但Startup.cs中的这一行:

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

答案 1 :(得分:0)

我会提出一些改进措施:

  1. 不要复制接收器配置,不需要在代码和appsettings中配置相同的接收器。选择一个,然后选择它。
  2. 构建ASP .NET Core以支持依赖注入。在ILogger<HelloController>中注入HelloController,而不是访问静态Log.Debug
  3. 感谢您找到问题并在问题中报告,这肯定会对其他开发者有所帮助。
  4. 对于Serilog和ASP .NET Core 2.1的一个非常小的例子,请看一下这个repo