跳過到頁腳內容
.NET幫助

Appmetrics C#(對於開發者的運行原理)

AppMetrics C# 是一個強大的工具,旨在簡化應用程式監控和性能分析。 通過 AppMetrics 抽象化,它簡化了跟踪應用程式各個方面的複雜性。 無論您使用的是 .NET Core 還是 .NET Framework,此 .NET 庫都能有效地記錄度量類型。 您可以檢索度量並利用 AppMetrics 支持的度量類型獲得全面的見解。

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

IronPDF: 高級 PDF 庫,適用於 C# 開發人員 是 C# 開發人員的另一個重要庫,特別是當處理 PDF 文件時。 它允許直接在 .NET Core 應用程式內創建、編輯和提取 PDF 文件。 這在需要從應用程式中生成報告、發票或任何其他 PDF 格式的文檔的情況下特別有用。

開始使用 AppMetrics

要將跨平台 AppMetrics 集成到您的 .NET 項目中,首先需要安裝 AppMetrics 庫。 您可以使用 .NET 的包管理器 NuGet 來完成此操作。 在您的項目中,運行以下命令於 NuGet 包管理器控制台中:

Install-Package App.Metrics.AspNetCore

Appmetrics C#(對開發人員的工作方式):圖1 - AppMetrics

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

一個基本的代碼示例:監控 HTTP 請求

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

public void ConfigureServices(IServiceCollection services)
{
    services.AddMetrics(); // Add basic metrics services
    services.AddMetricsTrackingMiddleware(); // Enable middleware for tracking
    services.AddMetricsEndpoints(); // Add endpoints for metrics exposure
}
public void ConfigureServices(IServiceCollection services)
{
    services.AddMetrics(); // Add basic metrics services
    services.AddMetricsTrackingMiddleware(); // Enable middleware for tracking
    services.AddMetricsEndpoints(); // Add endpoints for metrics exposure
}
Public Sub ConfigureServices(ByVal services As IServiceCollection)
	services.AddMetrics() ' Add basic metrics services
	services.AddMetricsTrackingMiddleware() ' Enable middleware for tracking
	services.AddMetricsEndpoints() ' Add endpoints for metrics exposure
End Sub
$vbLabelText   $csharpLabel

接下來,在相同文件的Configure方法中,確保添加了 AppMetrics 中間件以處理監控:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseMetricsAllMiddleware(); // Register the middleware to capture all metrics
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseMetricsAllMiddleware(); // Register the middleware to capture all metrics
}
Public Sub Configure(ByVal app As IApplicationBuilder, ByVal env As IWebHostEnvironment)
	app.UseMetricsAllMiddleware() ' Register the middleware to capture all metrics
End Sub
$vbLabelText   $csharpLabel

此設置會自動開始捕獲有關傳入 HTTP 請求的度量,例如請求數量、請求持續時間和錯誤率。

實施 AppMetrics 功能

記錄自定義度量

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

public class LoginTracker
{
    private readonly IMetrics _metrics;

    public LoginTracker(IMetrics metrics)
    {
        _metrics = metrics;
    }

    public void TrackLogin(string userId)
    {
        // Increment login counter for the specified user ID
        _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)
    {
        // Increment login counter for the specified user ID
        _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)
		' Increment login counter for the specified user ID
		_metrics.Measure.Counter.Increment(MetricsRegistry.Logins, New MetricTags("UserId", userId))
	End Sub
End Class
$vbLabelText   $csharpLabel

在這段代碼中,每當調用 TrackLogin 時,登錄計數器會針對指定的用戶 ID 增加。

測量應用程式性能

AppMetrics 還可以用來測量應用程式的性能。 例如,您可以使用計時器跟踪特定方法的持續時間:

public void ProcessData()
{
    // Measure time taken by the database query process
    using (_metrics.Measure.Timer.Time(MetricsRegistry.DatabaseQueryTimer))
    {
        // Code to execute a database query goes here
    }
}
public void ProcessData()
{
    // Measure time taken by the database query process
    using (_metrics.Measure.Timer.Time(MetricsRegistry.DatabaseQueryTimer))
    {
        // Code to execute a database query goes here
    }
}
Public Sub ProcessData()
	' Measure time taken by the database query process
	Using _metrics.Measure.Timer.Time(MetricsRegistry.DatabaseQueryTimer)
		' Code to execute a database query goes here
	End Using
End Sub
$vbLabelText   $csharpLabel

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

將度量報告到儀表盤

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

public void ConfigureServices(IServiceCollection services)
{
    services.AddMetricsReportingHostedService();
    services.AddMetrics(builder =>
    {
        builder.Report.ToInfluxDb(options =>
        {
            options.InfluxDb.BaseUri = new Uri("http://your-influxdb-server"); // Configure InfluxDB server URI
            options.InfluxDb.Database = "appmetricsdb"; // Specify the database name
            options.InfluxDb.UserName = "user"; // Set database username
            options.InfluxDb.Password = "password"; // Set database password
            options.HttpPolicy.BackoffPeriod = TimeSpan.FromSeconds(30); // Set backoff period
            options.HttpPolicy.FailuresBeforeBackoff = 5; // Set failure count before backoff
            options.HttpPolicy.Timeout = TimeSpan.FromSeconds(10); // Set HTTP timeout duration
            options.FlushInterval = TimeSpan.FromSeconds(5); // Set interval for reporting metrics
        });
    });
}
public void ConfigureServices(IServiceCollection services)
{
    services.AddMetricsReportingHostedService();
    services.AddMetrics(builder =>
    {
        builder.Report.ToInfluxDb(options =>
        {
            options.InfluxDb.BaseUri = new Uri("http://your-influxdb-server"); // Configure InfluxDB server URI
            options.InfluxDb.Database = "appmetricsdb"; // Specify the database name
            options.InfluxDb.UserName = "user"; // Set database username
            options.InfluxDb.Password = "password"; // Set database password
            options.HttpPolicy.BackoffPeriod = TimeSpan.FromSeconds(30); // Set backoff period
            options.HttpPolicy.FailuresBeforeBackoff = 5; // Set failure count before backoff
            options.HttpPolicy.Timeout = TimeSpan.FromSeconds(10); // Set HTTP timeout duration
            options.FlushInterval = TimeSpan.FromSeconds(5); // Set interval for reporting metrics
        });
    });
}
Public Sub ConfigureServices(ByVal services As IServiceCollection)
	services.AddMetricsReportingHostedService()
	services.AddMetrics(Sub(builder)
		builder.Report.ToInfluxDb(Sub(options)
			options.InfluxDb.BaseUri = New Uri("http://your-influxdb-server") ' Configure InfluxDB server URI
			options.InfluxDb.Database = "appmetricsdb" ' Specify the database name
			options.InfluxDb.UserName = "user" ' Set database username
			options.InfluxDb.Password = "password" ' Set database password
			options.HttpPolicy.BackoffPeriod = TimeSpan.FromSeconds(30) ' Set backoff period
			options.HttpPolicy.FailuresBeforeBackoff = 5 ' Set failure count before backoff
			options.HttpPolicy.Timeout = TimeSpan.FromSeconds(10) ' Set HTTP timeout duration
			options.FlushInterval = TimeSpan.FromSeconds(5) ' Set interval for reporting metrics
		End Sub)
	End Sub)
End Sub
$vbLabelText   $csharpLabel

跟踪內存使用

監控系統內存使用對於性能調整至關重要。 以下是如何跟踪可用內存的方法:

public void CheckSystemMemory()
{
    var freeMemory = GC.GetTotalMemory(false); // Get total free memory
    _metrics.Measure.Gauge.SetValue(MetricsRegistry.FreeMemory, freeMemory); // Set gauge to measure free memory
}
public void CheckSystemMemory()
{
    var freeMemory = GC.GetTotalMemory(false); // Get total free memory
    _metrics.Measure.Gauge.SetValue(MetricsRegistry.FreeMemory, freeMemory); // Set gauge to measure free memory
}
Public Sub CheckSystemMemory()
	Dim freeMemory = GC.GetTotalMemory(False) ' Get total free memory
	_metrics.Measure.Gauge.SetValue(MetricsRegistry.FreeMemory, freeMemory) ' Set gauge to measure free memory
End Sub
$vbLabelText   $csharpLabel

此量測計測量可用於您的應用程式的空閒內存,有助於了解內存消耗模式。

在指定的間隔處理度量

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

public void ConfigureScheduledReporting(IApplicationBuilder app)
{
    var metrics = app.ApplicationServices.GetService<IMetricsRoot>(); // Retrieve the IMetricsRoot instance
    var scheduler = new AppMetricsTaskScheduler(
        TimeSpan.FromSeconds(60), // Set the interval for metrics collection
        async () =>
        {
            await Task.WhenAll(metrics.ReportRunner.RunAllAsync()); // Run all reports asynchronously
        });
    scheduler.Start(); // Start the scheduler
}
public void ConfigureScheduledReporting(IApplicationBuilder app)
{
    var metrics = app.ApplicationServices.GetService<IMetricsRoot>(); // Retrieve the IMetricsRoot instance
    var scheduler = new AppMetricsTaskScheduler(
        TimeSpan.FromSeconds(60), // Set the interval for metrics collection
        async () =>
        {
            await Task.WhenAll(metrics.ReportRunner.RunAllAsync()); // Run all reports asynchronously
        });
    scheduler.Start(); // Start the scheduler
}
Public Sub ConfigureScheduledReporting(ByVal app As IApplicationBuilder)
	Dim metrics = app.ApplicationServices.GetService(Of IMetricsRoot)() ' Retrieve the IMetricsRoot instance
	Dim scheduler = New AppMetricsTaskScheduler(TimeSpan.FromSeconds(60), Async Sub()
			Await Task.WhenAll(metrics.ReportRunner.RunAllAsync()) ' Run all reports asynchronously
	End Sub)
	scheduler.Start() ' Start the scheduler
End Sub
$vbLabelText   $csharpLabel

此配置將度量設置為每 60 秒報告一次,確保一致的性能監控而不會用連續數據記錄淹沒系統。

將 AppMetrics 與 IronPDF 結合使用

當在 C# 應用程式中處理層次結構和 PDF 生成時,將 AppMetrics C# 與 IronPDF 結合使用非常有益。 此集成可讓您直接從度量數據生成 PDF 格式的報告,對於性能回顧、客戶演示甚至內部審計都大有幫助。

IronPDF 介紹

IronPDF 是一個全面的庫,允許開發人員使用 C# 創建、讀取和編輯 PDF 文件。 IronPDF 的獨特之處是它能夠將 HTML 轉換為 PDF,對於基於 Web 的報告生成特別有價值。 這一功能確保您的報告的視覺方面得以保留,從網頁到印刷表格提供了高度的保真度。

合併 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")
$vbLabelText   $csharpLabel

Appmetrics C#(對開發人員的工作方式):圖2 - PDF 報告輸出

此集成不僅自動化了報告生成的過程,還確保報告可以輕鬆閱讀且進行專業化格式化,非常適合任何利益相關者會議或存檔目的。

結論

Appmetrics C#(對開發人員的工作方式):圖3 - 許可

總之,將 AppMetrics C# 與 IronPDF 結合使用於您的 .NET 項目中,為應用程式性能監控和生成高質量 PDF 報告提供了一個健全的解決方案。 此集成使您可以無縫從使用 AppMetrics 捕獲詳盡的性能數據,從而使用 IronPDF 以清晰、專業化的格式呈現。

IronPDF 對於希望在其應用程式內管理 PDF 文件的 C# 開發人員特別有幫助。 它簡化了 PDF 文檔的創建和操作,並提供獨特的功能將 HTML 直接轉換為 PDF。 如果您考慮將 IronPDF 集成到您的項目中,他們提供 IronPDF 的免費試用版 以助您啟動,並且許可證從 $799 起價,為增強您的文檔處理能力提供經濟有效的方法。

常見問題解答

什麼是 AppMetrics C#,它如何為開發人員帶來好處?

AppMetrics C# 是一種設計用於應用程式監控和性能分析的工具,允許開發人員在 .NET Core 和 .NET Framework 中高效追蹤和檢索各種應用程式指標。

如何將 AppMetrics 集成到 .NET 項目中?

您可以通過在 NuGet 程序包管理器中使用命令來將 AppMetrics 集成到您的 .NET 項目中:Install-Package App.Metrics.AspNetCore

IronPDF 在從 AppMetrics 數據生成報告中扮演什麼角色?

IronPDF 可以通過將 HTML 格式的指標數據轉換成高質量的 PDF 來從 AppMetrics 數據生成綜合的 PDF 報告,非常適合性能評估和演示。

如何使用 AppMetrics 進行自定義指標的追蹤?

AppMetrics 允許您定義和追蹤自定義指標,例如用戶活動或特定交易時間,從而進行詳細的性能分析以滿足您的應用程式需求。

可視化 AppMetrics 數據有哪些選項?

AppMetrics 支援向各種儀表板報告,例如 InfluxDB,使開發人員能夠有效地可視化和監控指標數據。

開發人員如何使用 AppMetrics 優化應用程式性能?

開發人員可以使用 AppMetrics 監控內存使用和處理計劃指標,以確保有效的資源管理和應用程式反應能力來優化性能。

生成 IronPDF PDF 報告有什麼好處?

使用 IronPDF 從 AppMetrics 數據生成 PDF 報告提供了創建專業且易讀文件的優勢,增強了與利益相關者的溝通。

IronPDF 有免費試用版嗎?

是的,IronPDF 提供免費試用,允許開發人員在購買前探索其 PDF 生成能力。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。