【问题标题】:C# MVC Logging method execution and performanceC# MVC Logging 方法执行和性能
【发布时间】:2016-10-01 21:36:41
【问题描述】:

还有许多其他关于记录方法执行时间的帖子(例如通过postsharp、action filters 或通过自定义方法属性)。

因此,此时记录方法完成的时间相对简单。

然而,我希望做的是在每个请求的基础上获得更细粒度的性能指标,例如,利用会话 ID 来跟踪给定请求发生的所有操作 - 以及所有操作的时间流逝其中,不仅仅是父(即动作控制器)方法。

例如,我希望能够执行以下操作:

namespace MvcApplication1.Controllers
{
    public class ProductController : Controller
    {
        //record start of method 
        public ActionResult Index()
        {
            //record start of service1.method call
            var data = service1.method();
            //store total time of service1.method call

            //record start of db call
            var objects = db.select(obj).where(id=0)
            //store total time of db call

            return View();
        }
        //record total time of method
    }
}

理想情况下,我想将所有这些操作(父方法、服务调用和数据库调用)链接在一起——最有可能的候选者是通过会话 ID——但这意味着每个调用都需要访问会话身份证。

根据我的阅读,实现这一点的最佳方法是使用方法属性来记录父性能时间,然后使用某种自定义库函数来存储调用的各种时间(可能使用 nlog记录)。

我要的是关于完成上述任务的最佳方式(如果可能的话)的意见?

我是否遗漏了任何现有的第三方库 - 即 Unity 或 Postsharp 是否提供此功能(或其他一些库)?

是否可以通过会话 ID 链接所有这些记录?例如,我看不到如何通过 postsharp (1) 在 MVC 操作中存储单个方法调用,以及 (2) 在调用之间传递变量。

【问题讨论】:

    标签: c# asp.net-mvc unity-container postsharp


    【解决方案1】:

    根据您的问题,您需要记录与请求相关的所有操作。我将提供我的观点,希望对您有用。

    您是否会使用现有框架取决于很多原因,现在我将专注于自定义实现。

    首先,要完成这个问题,您需要一个日志结构:

    using System;
    
    public enum LogEntryType
    {
        Event,
        Message,
        Warning,
        Error
    }
    
    public class LogEntry
    {
        public int? LogEntryID { get; set; }
    
        public int? LogEntryType { get; set; }
    
        public DateTime? EntryDate { get; set; }
    
        public TimeSpan? ElapsedTime { get; set; }
    
        public string Key { get; set; }
    
        public string Description { get; set; }
    }
    

    接下来,您需要创建一个记录器对象并在您要记录的每个点上调用,例如:

    namespace MvcApp.Controllers
    {
        public class ProductController : Controller
        {
            protected ILogger Logger;
    
            public ProductController(ILogger logger;)
            {
                Logger = logger;
            }
    
            public ActionResult Index()
            {
                Logger.Write(LogEntry.Event, Server.SessionID, "Start of '{0}' action call", "Index");
    
    
                var serviceStopwatch = Stopwatch.StartNew();
    
                Logger.Write(LogEntry.Task, Server.SessionID, "Start of '{0}' task's execution", "GetData");
    
                var data = service.GetData();
    
                serviceStopwatch.Stop();
    
                Logger.Write(LogEntry.Task, Server.SessionID, serviceStopwatch.Elapsed, "End of '{0}' task's execution", "GetData");
    
    
                var dbCallStopwatch = Stopwatch.StartNew();
    
                Logger.Write(LogEntry.Task, Server.SessionID, "Start of '{0}' db call", "GetObjects");
    
                var objects = repository.GetObjects();
    
                dbCallStopwatch.Stop();
    
                Logger.Write(LogEntry.Task, Server.SessionID, dbCallStopwatch.Elapsed, "End of '{0}' db call", "GetObjects");
    
    
                Logger.Write(LogEntry.Event, Server.SessionID, "End of '{0}' action call", "Index");
    
                return View();
            }
        }
    }
    

    在上面的代码中,我们从服务器的会话 id(自动生成)中获取键的值来分组所有条目。

    Logger.Write 方法的签名应该是这样的:

    public void Write(LogEntryType logEntryType, string key, string message, params string[] args)
    {
        var item = new LogEntry
        {
            LogEntryType = (int?)logEntryType,
            EntryDate = DateTime.Now,
            Key = key,
            Description = string.Format(message, args)
        };
    
        // Code for save log entry to text file, database, send email if it's an error, etc.
    }
    
    public void Write(LogEntryType logEntryType, string key, TimeSpan elapsedTime, string message, params string[] args)
    {
        var item = new LogEntry
        {
            LogEntryType = (int?)logEntryType,
            EntryDate = DateTime.Now,
            ElapsedTime = elapsedTime,
            Key = key,
            Description = string.Format(message, args)
        };
    
        // Code for save log entry to text file, database, send email if it's an error, etc.
    }
    

    通常在实际的业务应用程序中,我们需要有执行指标和其他东西的工作流定义,但目前我不知道你想开发这个功能有多复杂。

    如果您将所有记录器的调用添加到所需的点并将它们全部保存到数据库(sql 或 nosql)中,接下来您将提取有关一个会话 id 事件的所有信息。

    如上所见,有一些日志条目类型定义:警告和错误,假设你添加try-catch块用于错误处理,如果有异常可以在catch块内记录:

    Logger.Write(LogEntry.Error, Server.SessionID, "There was an error on '{0}' task. Details: '{1}'", "Index", ex.Message);
    

    另外一点,最好实现异步操作以避免服务器阻塞请求。

    如果这个答案有意义,我们可以改进概念,这是解决问题的基本思路。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-04
      • 1970-01-01
      • 2011-01-19
      • 2015-03-01
      • 2017-03-28
      • 2013-05-25
      • 2012-05-11
      • 2021-09-14
      相关资源
      最近更新 更多