ASP.NET Core中的日志控制器操作持续时间 [英] log controller action time duration in ASP.NET core

查看:104
本文介绍了ASP.NET Core中的日志控制器操作持续时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于一项要求,我们需要记录aspnet核心操作请求的持续时间.在请求结束时,必须记录持续时间(秒表),我们还需要知道使用了哪个控制器和哪种操作方法.

For a requirement we need to log the duration for aspnet core action requests. At the end of the request the duration must be logged (stopwatch) and we also need to know which controller and which action method were used.

执行此操作的最佳位置是什么?动作过滤器,中间件?以及如何?

What is the best place to do this? Action filter, middleware? And how?

推荐答案

ASP.NET Core已经收集了此信息.您只需要确保它已被记录下来,就一般而言,并记录在您想要的位置即可.在开发中,这些被发送到控制台.如果您看到它,将会看到类似以下的日志:

ASP.NET Core already gathers this info. You just need to make sure it gets logged, in general, and where you want it to be. In development, these are sent to the console. If you watch that, you'll see logs like:

info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
    Request starting HTTP/1.1 GET http://localhost:44301/
...
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
    Route matched with {action = "Index", controller = "Home"}. Executing action MyApp.HomeController.Index (MyApp)
...
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
    Request finished in 7.981ms 200 text/html; charset=utf-8

您将感兴趣的主要类别是 Microsoft.AspNetCore.Hosting Microsoft.AspNetCore.Mvc ,它们都记录在 Information级别上.在生产环境中运行时,默认日志级别为警告,这就是为什么您没有将此日志记录到那里的原因.您可以简单地将一些内容添加到您的 appsettings.Production.json 文件中,例如:

The main categories you're going to be interested in are Microsoft.AspNetCore.Hosting and Microsoft.AspNetCore.Mvc, which both log at level Information. When running in production, the default log level is Warning, which is why you're not getting this logged there. You can simply add something to your appsettings.Production.json file like:

"Logging": {
  "LogLevel": {
    "Microsoft.AspNetCore.Hosting": "Information",
    "Microsoft.AspNetCore.Mvc": "Information"
  }
}

或者您可以指定仅记录特定提供商的日志:

Or you can specify logging to only a certain provider:

"Serilog": {
  "LogLevel": {
    "Microsoft.AspNetCore.Hosting": "Information",
    "Microsoft.AspNetCore.Mvc": "Information"
  }
}

您可以对此进行真正的细化和复杂化.请参阅日志上的文档过滤以获取更多信息.

You can get really granular and complex with this. See the docs on log filtering for more information.

这篇关于ASP.NET Core中的日志控制器操作持续时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆