当在owin中间件中使用LogConext.PushProperty向所有日志(log)事件添加关联ID时,它只会添加到中间件中,但不会在登录控制器时添加,这是我所期望的.
下面是代码与问题再现https://github.com/mk0sojo/SerilogOwinBug. 它是ASP.NET MVC on .NET framework模板,更改了以下内容:
- 添加Microsoft.Owin.Host.SystemWeb Nuget包以运行IIS中的OWIN中间件
- 从Nuget添加Serlog和Serilog.Sinks.Trace
- 在工程根目录下添加一个Startup.cs文件,文件内容如下:
using Microsoft.Owin;
using Owin;
using Serilog;
[assembly: OwinStartup(typeof(SerilogOwinBug.Startup))]
namespace SerilogOwinBug
{
public class Startup
{
// Running the app produces the following log:
// 2023-11-28 14:25:35Z [RequestId: 123] Starting middleware. URL: "/"
// 2023-11-28 14:25:35Z [RequestId: ] Hello from Home Controller
// 2023-11-28 14:25:37Z [RequestId: 123] Ending middleware. URL: "/"
//
// Expecting
// 2023-11-28 14:25:35Z [RequestId: 123] Starting middleware. URL: "/"
// 2023-11-28 14:25:35Z [RequestId: 123] Hello from Home Controller
// 2023-11-28 14:25:37Z [RequestId: 123] Ending middleware. URL: "/"
public Startup()
{
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.Trace(
outputTemplate: "{Timestamp:u} [RequestId: {RequestId}] {Message}"
)
.CreateLogger();
}
public void Configuration(IAppBuilder app)
{
app.Use<SerilogMiddleware>();
}
}
}
- 在项目根目录下添加SerilogMiddleware.cs:
using Microsoft.Owin;
using Serilog.Context;
using Serilog;
using System.Threading.Tasks;
namespace SerilogOwinBug
{
public class SerilogMiddleware : OwinMiddleware
{
public SerilogMiddleware(OwinMiddleware next) : base(next)
{
}
public override async Task Invoke(IOwinContext context)
{
using (LogContext.PushProperty("RequestId", "123"))
{
Log.Information("Starting middleware. URL: {URL}", context.Request.Path);
await Next.Invoke(context);
Log.Information("Ending middleware. URL: {URL}", context.Request.Path);
}
}
}
}
- 将一条日志(log)语句添加到HomeController.cs文件,使其如下所示:
using Serilog;
using System.Web.Mvc;
namespace SerilogOwinBug.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
Log.Information("Hello from Home Controller");
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
}
- 运行应用程序并在Web浏览器中打开它.判断输出窗口中的日志(log).它看起来是这样的:
iisexpress.exe Information: 0 : 2023-11-28 14:25:35Z [RequestId: 123] Starting middleware. URL: "/"
iisexpress.exe Information: 0 : 2023-11-28 14:25:35Z [RequestId: ] Hello from Home Controller
...
iisexpress.exe Information: 0 : 2023-11-28 14:25:37Z [RequestId: 123] Ending middleware. URL: "/"
Expected behavior个 预计输出为:
iisexpress.exe Information: 0 : 2023-11-28 14:25:35Z [RequestId: 123] Starting middleware. URL: "/"
iisexpress.exe Information: 0 : 2023-11-28 14:25:35Z [RequestId: 123] Hello from Home Controller
...
iisexpress.exe Information: 0 : 2023-11-28 14:25:37Z [RequestId: 123] Ending middleware. URL: "/"