.NET 幫助

Appmetrics C#(它如何為開發者工作)

發佈 2024年7月1日
分享:

AppMetrics C# 是一個強大的工具,旨在簡化應用程式監控和性能分析。使用 App Metrics 抽象,能夠簡化跟踪應用程式各個方面的複雜性。無論您是使用 .NET Core 還是 .NET Framework,這個 .NET 函式庫都能讓您有效地記錄各種指標類型。您可以檢索指標並利用 App Metrics 支援的指標類型獲取全面的洞察。

這個 .NET 函式庫支援檢索指標,並允許您在指定的間隔內刷新指標,確保及時的數據收集。它還提供了一個擴展方法,提供可擴展性點以增強靈活性。作為跨平台解決方案,App Metrics 適合多種環境,並確保一致的性能監控。

IronPDF 是 C# 開發者另一個必不可少的庫,特別是在處理 PDF 文件時。它允許在 .NET Core 應用程序中直接創建、編輯和提取 PDF 文件。在需要從應用程序生成報告、發票或任何其他 PDF 格式文件的情況下,這特別有用。

開始使用 AppMetrics

要將跨平台的 App Metrics 集成到您的 .NET 專案中,您首先需要安裝 AppMetrics 庫。您可以使用 .NET 的包管理器 NuGet 套件來完成此操作。在您的專案中,在 NuGet Package Manager Console 中運行以下命令:

Install-Package App.Metrics.AspNetCore
Install-Package App.Metrics.AspNetCore
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'Install-Package App.Metrics.AspNetCore
VB   C#

Appmetrics C#(開發者如何使用):圖 1 - AppMetrics

此命令將所有必要的依賴項添加到您的項目中,使您可以開始配置AppMetrics。

基本代碼範例:監控 HTTP 請求

以下是如何在 .NET 應用程序中使用 AppMetrics 設置基本的 HTTP 請求監控。首先,在你的 Startup.cs 文件中建立度量。將以下代碼添加到 ConfigureServices 方法中:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMetrics(); // metric type
    services.AddMetricsTrackingMiddleware();
    services.AddMetricsEndpoints();
}
public void ConfigureServices(IServiceCollection services)
{
    services.AddMetrics(); // metric type
    services.AddMetricsTrackingMiddleware();
    services.AddMetricsEndpoints();
}
Public Sub ConfigureServices(ByVal services As IServiceCollection)
	services.AddMetrics() ' metric type
	services.AddMetricsTrackingMiddleware()
	services.AddMetricsEndpoints()
End Sub
VB   C#

接下來,在相同檔案的 Configure 方法中,確保添加 AppMetrics 中介軟體來處理監控:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseMetricsAllMiddleware();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseMetricsAllMiddleware();
}
Public Sub Configure(ByVal app As IApplicationBuilder, ByVal env As IWebHostEnvironment)
	app.UseMetricsAllMiddleware()
End Sub
VB   C#

此設定會自動開始捕捉關於進入您應用程式的 HTTP 請求的指標,例如請求數量、請求持續時間和錯誤率。

實現應用程序度量功能

記錄自訂指標

為了在您的應用程式中創建和記錄自訂指標或度量事物,AppMetrics 提供了一種靈活的方法來定義需要跟踪的內容。以下是一個記錄簡單計數器以跟踪用戶登錄的範例:

public class LoginTracker
{
    private readonly IMetrics _metrics;
    public LoginTracker(IMetrics metrics)
    {
        _metrics = metrics;
    }
    public void TrackLogin(string userId)
    {
        _metrics.Measure.Counter.Increment(MetricsRegistry.Logins, new MetricTags("UserId", userId));
    }
}
public class LoginTracker
{
    private readonly IMetrics _metrics;
    public LoginTracker(IMetrics metrics)
    {
        _metrics = metrics;
    }
    public void TrackLogin(string userId)
    {
        _metrics.Measure.Counter.Increment(MetricsRegistry.Logins, new MetricTags("UserId", userId));
    }
}
Public Class LoginTracker
	Private ReadOnly _metrics As IMetrics
	Public Sub New(ByVal metrics As IMetrics)
		_metrics = metrics
	End Sub
	Public Sub TrackLogin(ByVal userId As String)
		_metrics.Measure.Counter.Increment(MetricsRegistry.Logins, New MetricTags("UserId", userId))
	End Sub
End Class
VB   C#

在此程式碼中,每次呼叫 TrackLogin 時,指定使用者 ID 的登入計數器會增加。

測量應用程式效能

AppMetrics 也可以用來測量應用程式的效能。例如,您可以使用計時器來追踪特定方法的執行時間:

public void ProcessData()
{
    using (_metrics.Measure.Timer.Time(MetricsRegistry.DatabaseQueryTimer))
    {
        // Code to execute a database query
    }
}
public void ProcessData()
{
    using (_metrics.Measure.Timer.Time(MetricsRegistry.DatabaseQueryTimer))
    {
        // Code to execute a database query
    }
}
Public Sub ProcessData()
	Using _metrics.Measure.Timer.Time(MetricsRegistry.DatabaseQueryTimer)
		' Code to execute a database query
	End Using
End Sub
VB   C#

此計時器記錄 ProcessData 方法執行所需的時間,提供有關資料庫查詢效能的見解。

將報告指标到儀表板

為了可視化和監控各種指標類型,AppMetrics 可以將數據報告到不同的儀表板。以下是如何配置報告到 InfluxDB 儀表板的方法:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMetricsReportingHostedService();
    services.AddMetricsBuild(builder =>
    {
        builder.Report.ToInfluxDb(options =>
        {
            options.InfluxDb.BaseUri = new Uri("http://your-influxdb-server");
            options.InfluxDb.Database = "appmetricsdb";
            options.InfluxDb.UserName = "user";
            options.InfluxDb.Password = "password";
            options.HttpPolicy.BackoffPeriod = TimeSpan.FromSeconds(30);
            options.HttpPolicy.FailuresBeforeBackoff = 5;
            options.HttpPolicy.Timeout = TimeSpan.FromSeconds(10);
            options.FlushInterval = TimeSpan.FromSeconds(5);
        });
    });
}
public void ConfigureServices(IServiceCollection services)
{
    services.AddMetricsReportingHostedService();
    services.AddMetricsBuild(builder =>
    {
        builder.Report.ToInfluxDb(options =>
        {
            options.InfluxDb.BaseUri = new Uri("http://your-influxdb-server");
            options.InfluxDb.Database = "appmetricsdb";
            options.InfluxDb.UserName = "user";
            options.InfluxDb.Password = "password";
            options.HttpPolicy.BackoffPeriod = TimeSpan.FromSeconds(30);
            options.HttpPolicy.FailuresBeforeBackoff = 5;
            options.HttpPolicy.Timeout = TimeSpan.FromSeconds(10);
            options.FlushInterval = TimeSpan.FromSeconds(5);
        });
    });
}
Public Sub ConfigureServices(ByVal services As IServiceCollection)
	services.AddMetricsReportingHostedService()
	services.AddMetricsBuild(Sub(builder)
		builder.Report.ToInfluxDb(Sub(options)
			options.InfluxDb.BaseUri = New Uri("http://your-influxdb-server")
			options.InfluxDb.Database = "appmetricsdb"
			options.InfluxDb.UserName = "user"
			options.InfluxDb.Password = "password"
			options.HttpPolicy.BackoffPeriod = TimeSpan.FromSeconds(30)
			options.HttpPolicy.FailuresBeforeBackoff = 5
			options.HttpPolicy.Timeout = TimeSpan.FromSeconds(10)
			options.FlushInterval = TimeSpan.FromSeconds(5)
		End Sub)
	End Sub)
End Sub
VB   C#

追蹤記憶體使用量

監控系統記憶體使用量對於性能調整至關重要。以下是如何追蹤可用記憶體的方法:

public void CheckSystemMemory()
{
    var freeMemory = GC.GetTotalMemory(false);
    _metrics.Measure.Gauge.SetValue(MetricsRegistry.FreeMemory, freeMemory);
}
public void CheckSystemMemory()
{
    var freeMemory = GC.GetTotalMemory(false);
    _metrics.Measure.Gauge.SetValue(MetricsRegistry.FreeMemory, freeMemory);
}
Public Sub CheckSystemMemory()
	Dim freeMemory = GC.GetTotalMemory(False)
	_metrics.Measure.Gauge.SetValue(MetricsRegistry.FreeMemory, freeMemory)
End Sub
VB   C#

這個儀表測量應用程式可用的空閒記憶體,幫助您了解記憶體消耗模式。

在指定間隔處理度量

AppMetrics 可以配置為在指定間隔內處理度量收集。這有助於在不過於頻繁記錄數據的情況下維持性能:

public void ConfigureScheduledReporting(IApplicationBuilder app)
{
    var metrics = app.ApplicationServices.GetService<IMetricsRoot>();
    var scheduler = new AppMetricsTaskScheduler(
        TimeSpan.FromSeconds(60),
        async () =>
        {
            await Task.WhenAll(metrics.ReportRunner.RunAllAsync()); // await task
        });
    scheduler.Start();
}
public void ConfigureScheduledReporting(IApplicationBuilder app)
{
    var metrics = app.ApplicationServices.GetService<IMetricsRoot>();
    var scheduler = new AppMetricsTaskScheduler(
        TimeSpan.FromSeconds(60),
        async () =>
        {
            await Task.WhenAll(metrics.ReportRunner.RunAllAsync()); // await task
        });
    scheduler.Start();
}
Public Sub ConfigureScheduledReporting(ByVal app As IApplicationBuilder)
	Dim metrics = app.ApplicationServices.GetService(Of IMetricsRoot)()
	Dim scheduler = New AppMetricsTaskScheduler(TimeSpan.FromSeconds(60), Async Sub()
			Await Task.WhenAll(metrics.ReportRunner.RunAllAsync()) ' await task
	End Sub)
	scheduler.Start()
End Sub
VB   C#

此配置將每60秒報告一次指標,在確保一致性能監控的同時,不會因為持續的數據記錄而使系統不堪重負。

將 AppMetrics 與 IronPDF 整合

在 C# 應用程式中處理指標和 PDF 生成時,將 AppMetrics C# 與 IronPDF 結合使用會非常有利。此整合使您可以直接從指標數據生成 PDF 格式的報告,這對於性能評估、客戶演示或甚至內部審計都非常有用。

IronPDF 簡介

IronPDF 是一個全面的程式庫,使開發人員能夠使用 C# 來建立、閱讀和編輯 PDF 文件。IronPDF 的特點在於它的能力 將 HTML 轉換為 PDF,這使它在基於網頁的報告生成中特別有價值。此功能確保您的報告的視覺效果得以保留,從網頁到列印形式提供高度的保真度。

將IronPDF與AppMetrics C#合併后的使用案例

考慮一種情況,您需要向利益相關者提供應用程式的每月性能報告。這些報告包括響應時間、錯誤率、用戶會話等指標。通過開源的AppMetrics C#,您可以毫不費力地捕獲這些指標。通過將此功能與IronPDF合併,您可以自動生成並分發這些格式整齊的PDF文檔中的指標。

用例的代碼範例

以下是一個完整的實現示例。此示例假設您已經在項目中設置了 IronPDF 和 AppMetrics C#。

using App.Metrics;
using App.Metrics.Formatters.Prometheus;
using IronPdf;
public class MetricsToPdfConverter
{
    private readonly IMetricsRoot _metrics;
    public MetricsToPdfConverter(IMetricsRoot metrics)
    {
        _metrics = metrics;
    }
    public void GeneratePdfReport(string outputPath)
    {
        // Step 1: Capture the metrics snapshot
        var metricsData = _metrics.Snapshot.Get();
        var formatter = new MetricsPrometheusTextOutputFormatter();
        using var stream = new MemoryStream();
        formatter.WriteAsync(stream, metricsData).Wait();
        // Step 2: Convert the metrics snapshot to string format
        stream.Position = 0;
        var reader = new StreamReader(stream);
        var metricsText = reader.ReadToEnd();
        // Step 3: Use IronPDF to convert the metrics text to a PDF document
        var renderer = new ChromePdfRenderer();
        var pdf = renderer.RenderHtmlAsPdf("<h1> Metrics Report </h1> <pre>" + metricsText + "</pre>");
        // Step 4: Save the PDF document
        pdf.SaveAs(outputPath);
    }
}
// Usage
var metrics = new MetricsBuilder().Build();
var pdfConverter = new MetricsToPdfConverter(metrics);
pdfConverter.GeneratePdfReport("MonthlyPerformanceReport.pdf");
using App.Metrics;
using App.Metrics.Formatters.Prometheus;
using IronPdf;
public class MetricsToPdfConverter
{
    private readonly IMetricsRoot _metrics;
    public MetricsToPdfConverter(IMetricsRoot metrics)
    {
        _metrics = metrics;
    }
    public void GeneratePdfReport(string outputPath)
    {
        // Step 1: Capture the metrics snapshot
        var metricsData = _metrics.Snapshot.Get();
        var formatter = new MetricsPrometheusTextOutputFormatter();
        using var stream = new MemoryStream();
        formatter.WriteAsync(stream, metricsData).Wait();
        // Step 2: Convert the metrics snapshot to string format
        stream.Position = 0;
        var reader = new StreamReader(stream);
        var metricsText = reader.ReadToEnd();
        // Step 3: Use IronPDF to convert the metrics text to a PDF document
        var renderer = new ChromePdfRenderer();
        var pdf = renderer.RenderHtmlAsPdf("<h1> Metrics Report </h1> <pre>" + metricsText + "</pre>");
        // Step 4: Save the PDF document
        pdf.SaveAs(outputPath);
    }
}
// Usage
var metrics = new MetricsBuilder().Build();
var pdfConverter = new MetricsToPdfConverter(metrics);
pdfConverter.GeneratePdfReport("MonthlyPerformanceReport.pdf");
Imports App.Metrics
Imports App.Metrics.Formatters.Prometheus
Imports IronPdf
Public Class MetricsToPdfConverter
	Private ReadOnly _metrics As IMetricsRoot
	Public Sub New(ByVal metrics As IMetricsRoot)
		_metrics = metrics
	End Sub
	Public Sub GeneratePdfReport(ByVal outputPath As String)
		' Step 1: Capture the metrics snapshot
		Dim metricsData = _metrics.Snapshot.Get()
		Dim formatter = New MetricsPrometheusTextOutputFormatter()
		Dim stream = New MemoryStream()
		formatter.WriteAsync(stream, metricsData).Wait()
		' Step 2: Convert the metrics snapshot to string format
		stream.Position = 0
		Dim reader = New StreamReader(stream)
		Dim metricsText = reader.ReadToEnd()
		' Step 3: Use IronPDF to convert the metrics text to a PDF document
		Dim renderer = New ChromePdfRenderer()
		Dim pdf = renderer.RenderHtmlAsPdf("<h1> Metrics Report </h1> <pre>" & metricsText & "</pre>")
		' Step 4: Save the PDF document
		pdf.SaveAs(outputPath)
	End Sub
End Class
' Usage
Private metrics = (New MetricsBuilder()).Build()
Private pdfConverter = New MetricsToPdfConverter(metrics)
pdfConverter.GeneratePdfReport("MonthlyPerformanceReport.pdf")
VB   C#

Appmetrics C#(它如何對開發人員起作用):圖 2 - PDF 報告輸出

此整合不僅自動化報告生成過程,還確保報告易讀且格式專業,非常適合任何利害關係人會議或存檔目的。

結論

Appmetrics C# (開發者如何運作): 圖3 - 許可證

總結來說,在您的 .NET 專案中結合 AppMetrics C# 和 IronPDF 為應用程式效能監控和生成高品質的 PDF 報告提供了一個強大的解決方案。這種整合讓您可以無縫地從使用 AppMetrics 捕捉詳細的性能數據過渡到使用 IronPDF 以清晰、專業的格式呈現。

IronPDF 對於尋求在其應用程式內處理 PDF 文件的 C# 開發人員特別有益。它簡化了 PDF 文件的創建和操作,並提供直接將 HTML 轉換為 PDF 的獨特能力。如果您正在考慮將 IronPDF 整合到您的專案中,他們提供了一个 免費試用 提供起步方案,授權價格從 $749 起,提供經濟實惠的方式來增強您的文件處理能力。

< 上一頁
C# 解構函式 (開發者如何使用)
下一個 >
Mathnet.Numerics C#(它如何為開發人員運作)

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >