在微服务架构中,应用程序性能监控(Application Performance Monitoring,APM)是必不可少的一环。Elastic APM 是一个开源的、分布式的 APM 解决方案,可以帮助开发人员实时监控应用程序的性能,并提供详细的性能指标和故障排查信息。在本博客中,我们将介绍如何将 Elastic APM 集成到 ASP.NET Core WebAPI 中,并监控 WebAPI 的性能。
步骤一:安装 Elastic APM NuGet 包
首先,我们需要通过 NuGet 包管理器将 Elastic APM 包安装到 ASP.NET Core WebAPI 项目中。打开 Visual Studio,右键单击项目文件,然后选择“Manage NuGet Packages”菜单。在NuGet包管理器中,搜索并安装 Elastic.Apm.All
包。
步骤二:配置 Elastic APM
在 ASP.NET Core WebAPI 项目的 Startup.cs
文件中,我们需要配置 Elastic APM。找到 ConfigureServices
方法,并添加以下代码:
services.AddElasticApm(options =>
{
options.ServiceName = "MyWebAPI";
options.ServerUrls = "http://localhost:8200";
});
在上面的代码中,我们通过 AddElasticApm
方法将 Elastic APM 添加到依赖注入容器中,然后配置了服务名称和服务器 URL。你可以根据自己的需求进行更改。
步骤三:性能追踪
接下来,我们需要在代码中添加自定义的性能追踪。在你的控制器类或者一些重要的方法中,你可以使用 Elastic.Apm.Api.Tracer
的 CaptureTransaction
和 CaptureSpan
方法来手动追踪性能。例如:
using Elastic.Apm.Api;
[ApiController]
[Route("api/[controller]")]
public class ExampleController : ControllerBase
{
private readonly ILogger<ExampleController> _logger;
public ExampleController(ILogger<ExampleController> logger)
{
_logger = logger;
}
[HttpGet("{id}")]
public ActionResult<string> Get(int id)
{
using (var transaction = Tracer.Current.CaptureTransaction("MyTransaction", ApiConstants.TypeRequest))
{
transaction.Context.Request.Method = HttpContext.Request.Method;
transaction.Context.Request.Url = HttpContext.Request.Path;
using (var span = transaction.CaptureSpan("MySpan", ApiConstants.ActionExec))
{
span.Labels["id"] = id.ToString();
span.Labels["controller"] = nameof(ExampleController);
// 你的代码逻辑
return "OK";
}
}
}
}
在上面的代码中,我们在 Get
方法中手动创建了一个事务(Transaction)和一个跟踪片段(Span)。事务用于跟踪整个请求的性能,而跟踪片段用于跟踪方法内的性能。
步骤四:启动 Elastic APM 服务器
最后,在你的开发环境中启动 Elastic APM 服务器。你可以从 Elastic APM 官方网站 下载并安装 Elastic APM 服务器包。安装完成后,在命令行中运行以下命令:
./apm-server -e
这将启动 Elastic APM 服务器,并监听默认端口 8200
。你可以在 options.ServerUrls
中配置其他的服务器 URL。
结论
通过以上步骤,我们已经成功将 Elastic APM 集成到 ASP.NET Core WebAPI 中,并可以实时监控 WebAPI 的性能了。Elastic APM 提供了丰富的性能指标和故障排查信息,帮助开发人员更好地理解和优化应用程序的性能。希望这篇博客对你有所帮助!
参考链接:
本文来自极简博客,作者:科技前沿观察,转载请注明原文链接:ASP.NET Core WebAPI 如何接入 Elastic APM