根据您的问题,您需要记录与请求相关的所有操作。我将提供我的观点,希望对您有用。
您是否会使用现有框架取决于很多原因,现在我将专注于自定义实现。
首先,要完成这个问题,您需要一个日志结构:
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);
另外一点,最好实现异步操作以避免服务器阻塞请求。
如果这个答案有意义,我们可以改进概念,这是解决问题的基本思路。