应用性能监控

Performance monitoring of application

我想要包含以下信息的特殊性能日志 一行http请求

我现在使用 serilog 来记录未处理的异常。添加这种日志插入的理想位置在哪里或最佳实践是什么?将日志存储到数据库中是一种很好的做法?

如果您希望它简单并使用您自己的解决方案,您可以为 asp.net 核心管道编写一个 Middleware 来跟踪所需的数据。

我不建议使用 Serilog 来保存收集到的信息。 Serilog 是一个日志记录框架,不应用于跟踪应用程序指标。

直接使用数据库(sql、mongo 等)来存储和分析您的数据。您已经在问题中定义了对象模型,因此您应该可以轻松地在数据库中创建和保存模型实例。

为什么不查看 APM 工具或跟踪工具来执行此操作,而不是仅使用不允许您实际识别和解决问题的数据创建日志。 APm 工具提供的价值远不止记录性能数据,而是让您能够解决问题。该领域的领导者是 AppDynamics、New Relic 和 Dynatrace。有许多开源工具也可以在这方面提供帮助,例如 Zipkin、Jaeger 和 Skywalking。您可能还想解释一下您的应用程序的架构和语言:)

中间件方法似乎可行。

public class PerformanceMiddleware
    {
        private readonly RequestDelegate next;
        private readonly IConfiguration _configuration;
        private readonly ILogger _logger;

        public PerformanceMiddleware(RequestDelegate next, IConfiguration configuration, ILogger<PerformanceMiddleware> logger)
        {
            _configuration = configuration;
            _logger = logger;
            this.next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();

            await next.Invoke(context);

            stopwatch.Stop();

            try
            {
                using (var conn = new SqlConnection(_configuration.GetConnectionString("DefaultConnection")))
                using (var command = new SqlCommand("dbo.usp_insertPerformance", conn) { CommandType = CommandType.StoredProcedure })
                {
                    conn.Open();

                    // set parameters
                    command.ExecuteNonQuery();
                }
            }
            // We dont want show this error to user.
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error in PerformanceMiddleware database operation.");
            }

        }
    }