如何在ASP.NET Core 2.2中监听输出日志

时间:2019-02-02 13:00:32

标签: c# asp.net-core asp.net-core-webapi

我正在使用ASP.NET Core 2.2开发API服务器,而我的服务器计算机是Ubuntu 18.04。

我有一个日志文件为我的API的状态,但我觉得缺乏对ASP.NET(红隼)状态信息,如路由结果我的控制器。

ASP.NET生成如下所示的日志。

ServerApplication> info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
ServerApplication>       Request starting HTTP/1.1 GET  
                         http://localhost:57904/api  
ServerApplication> info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
ServerApplication>       Request starting HTTP/1.1 DEBUG
                         http://localhost:57904/  0
ServerApplication> info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
ServerApplication>       Request finished in 36.827ms 200 
ServerApplication> info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]

我想收听或捕获这些日志以放入我的日志文件中。

我读过this article,但似乎不是在谈论听日志。

如何解决此问题?

1 个答案:

答案 0 :(得分:1)

我刚刚调整了Serilog.Extensions.Logging.File

using Serilog;
using Serilog.Core;
using Serilog.Events;

public void Configure(IApplicationBuilder app,
                      IHostingEnvironment env,
                      ILoggerFactory loggerFactory)
{
    loggerFactory.AddSerilog(
        new LoggerConfiguration()
            .Enrich.FromLogContext()
            .WriteTo.Sink(new LogEventSink())
            .CreateLogger());
}

public class LogEventSink : ILogEventSink
{
    public void Emit(LogEvent logEvent)
    {
        string message = logEvent.RenderMessage();
        // Write to my log.
    }
}