Creating Application Performance Counters with C#/.NET

Wednesday, January 06, 2010 05:42 PM

Always wanted to know how to make your own performance counters? Check out the code below. There is a slight caveat. The very first time you execute this code it will create the category and associated counters. When that occurs the process that's running must be an administrator. Best practice might be to handle counter creation in a pre-deploy step.

using System.Diagnostics;

public class MyCounters
{
    private const string MASTER_CATEGORY = "My Company Category";
    private const string MASTER_CATEGORY_HELP = "My Company Application Counters";
    private const string QUEUE_COUNTER = "My Application Message Queue Count";
    private CounterCreationDataCollection counters = new CounterCreationDataCollection();
    private CounterCreationData queueCount = new CounterCreationData();
    private PerformanceCounter queueCounter = new PerformanceCounter();

    public MyApplicationCounters()
    {
        if (!PerformanceCounterCategory.Exists(MASTER_CATEGORY))
        {
            queueCount.CounterName = QUEUE_COUNTER;
            queueCount.CounterHelp = "Total number of items in the queue.";
            queueCount.CounterType = PerformanceCounterType.NumberOfItems32;
            counters.Add(queueCount);

            PerformanceCounterCategory.Create(MASTER_CATEGORY, MASTER_CATEGORY_HELP, PerformanceCounterCategoryType.MultiInstance, counters);
        }

        queueCounter.CategoryName = MASTER_CATEGORY;
        queueCounter.CounterName = QUEUE_COUNTER;
        queueCounter.MachineName = ".";
        queueCounter.InstanceName = "_Total";
        queueCounter.ReadOnly = false;
    }

    public int MessageQueueCount
    {
        get
        {
            return (int)queueCounter.RawValue;
        }
        set
        {
            queueCounter.RawValue = value;
        }
    }
}