Course contentsShow
← C#
Lesson 1804 of 1,90816. Performance and DiagnosticsFree lesson

Logging Performance Metrics as Events

Learners will treat performance counters as first-class logs for time-series analysis.

In this lesson, you will learn how to shift your mindset from treating performance data as ephemeral "gauges" to treating them as first-class, immutable log events optimized for time-series analysis.

Moving Beyond Snapshots

In previous lessons, we discussed log throughput and structuring data for machine analytics. When we monitor performance, it is common to log a single value, like CPU usage: 45%. However, for high-traffic applications, a static snapshot is often insufficient. To perform effective time-series analysis—such as calculating percentiles (P99) or identifying trends over time—you must log metrics as discrete events.

By treating a performance metric as an event, you preserve the exact context (the correlation ID, the service version, and the host metadata) alongside the measurement. This allows you to reconstruct the state of the system at the exact moment a latency spike occurred.

Implementing Metric Events

Instead of updating a global counter in memory, emit an event containing the metric payload. This ensures your logging pipeline treats the metric with the same consistency as your diagnostic logs.

public void LogLatencyEvent(string operationName, long elapsedMilliseconds, string correlationId)
{
    // Treat the metric as a structured event
    var performanceEvent = new
    {
        EventName = "OperationLatency",
        Operation = operationName,
        DurationMs = elapsedMilliseconds,
        CorrelationId = correlationId,
        Timestamp = DateTime.UtcNow
    };

    _logger.LogInformation("Performance Metric: {@PerformanceEvent}", performanceEvent);
}

Why Time-Series Analysis Matters

When performance metrics are logged as events, they become queryable in your ELK stack or other analytical tools. You no longer just see "high latency"; you can write queries to aggregate these events over 5-minute buckets. Because the metrics are correlated with the CorrelationID from your request tracing, you can jump directly from a slow P99 event to the specific distributed trace that caused it.

Avoid the temptation to summarize data before logging. By logging the raw measurement as a structured event, you retain the granularity required for modern diagnostics, allowing the downstream analytical engine to perform the aggregation.

Key Takeaway: Treat performance metrics as immutable, structured log events to enable deep time-series analysis and correlate system health directly with individual request traces.