我创建了一个新的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.
答案 0 :(得分:0)
找到它:
这不是我的控制器返回&#34; Hello world&#34;但Startup.cs
中的这一行:
app.Run(async (context) => { await context.Response.WriteAsync("Hello World!"); });
答案 1 :(得分:0)
我会提出一些改进措施:
ILogger<HelloController>
中注入HelloController
,而不是访问静态Log.Debug
。对于Serilog和ASP .NET Core 2.1的一个非常小的例子,请看一下这个repo。