[英]How to log the selected ASP.NET Core MVC route?
Is there a simple way to log (using nlog, eg log.Debug(…)
) the selected route in an ASP.NET Core MVC application?在 ASP.NET Core MVC 应用程序中是否有一种简单的方法来记录(使用 nlog,例如
log.Debug(…)
)选定的路由? I use HttpGet
/ HttpPost
attributes to define my routes, and I am looking for a simple way to log the route that MVC chooses to handle for each incoming request.我使用
HttpGet
/ HttpPost
属性来定义我的路由,并且我正在寻找一种简单的方法来记录 MVC 为每个传入请求选择处理的路由。
Note: Similar questions have been answered, but they relate to debugging and analyzing routes:
注意:已经回答了类似的问题,但它们与调试和分析路由有关:
For my purposes, though, I just want to know which route MVC chose to handle for the request and have it logged.不过,出于我的目的,我只想知道 MVC 选择了哪个路由来处理请求并记录它。 (And, ideally, I don't want to add a log to each controller method; there must be some way to do this once generically for all incoming requests.)
(而且,理想情况下,我不想为每个 controller 方法添加日志;必须有某种方法可以对所有传入请求进行一次通用操作。)
a simple generic way of logging all request is using a registered middleware component.记录所有请求的简单通用方法是使用已注册的中间件组件。
public class PerformanceMiddleware
{
private readonly RequestDelegate _next;
public PerformanceMiddleware(RequestDelegate requestDelegate)
{
_next = requestDelegate;
}
public Task Invoke(HttpContext httpContext)
{
var watch = new Stopwatch();
watch.Start();
var nextTask = _next.Invoke(httpContext);
nextTask.ContinueWith(t =>
{
var time = watch.ElapsedMilliseconds;
var requestString = $"[{httpRequest.Method}]{httpRequest.Path}?{httpRequest.QueryString}";
if (t.Status == TaskStatus.RanToCompletion)
{
.. log.Info ..($"{time}ms {requestString}");
}
else
{
.. log.Warn ..($"{time}ms [{t.Status}] - {requestString}", t.Exception?.InnerException);
}
});
return nextTask;
}
}
this also logs the execution time这也记录了执行时间
In your startup you register it as the first, before UseMvc
and any other middleware components.在您的启动中,您将其注册为第一个,在
UseMvc
和任何其他中间件组件之前。
app.UseMiddleware<PerformanceMiddleware>();
On IIS, you can use the web.config
file.在 IIS 上,您可以使用
web.config
文件。 In this file, by default, there is an option stdoutLogEnabled=false
.在这个文件中,默认情况下,有一个选项
stdoutLogEnabled=false
。 Switch it to true
.将其切换为
true
。 A log will be generated with the info you want.将使用您想要的信息生成日志。
Edit: Updated my answer to specify it's only correct for IIS according to the comments below编辑:根据以下评论更新了我的答案以指定它仅适用于 IIS
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.