Skip to content
Hintea Dan Alexandru edited this page Mar 30, 2016 · 9 revisions

Counters represent 64-bit integer values that can be incremented and decremented.

Counters are registered by calling the appropriate methods on the static Metric class or on a child MetricsContext. See metrics grouping & organization for details.

Simple counter sample
public class Cache
{
    private static readonly Counter counter =
        Metric.Counter("ItemsInCache", Unit.Items);

    private void AddItems(object[] items)
    {
        counter.Increment(items.Length);
    }

    private void AddItem(object item)
    {
        counter.Increment();
    }

    private void RemoveItem(object item)
    {
        counter.Decrement();
    }
}
Counting values from a set

The Counter also provides the ability to track counters for each item from a finite set. For example, you have a system that processes a set of commands. In the Process method you need to count the total number of commands processed, but would also like to have a counter for each command type. If the number of commands is large, manually defining and incrementing each counter can be hard.

Luckily the counter can keep track of sub-counters for you:

public class SetCounterSample
{
    private readonly Counter commandCounter = 
        Metric.Counter("Command Counter", Unit.Custom("Commands"));

    public interface Command { }
    public class SendEmail : Command { }
    public class ShipProduct : Command { }
    public class BillCustomer : Command { }
    public class MakeInvoice : Command { }
    public class MarkAsPreffered : Command { }

    public void Process(Command command)
    {
        this.commandCounter.Increment(command.GetType().Name);

        // do actual command processing
    }
}

After running a few requests, the output of the counter in text format looks like this:

    Command Counter
             Count = 2550 Commands
       Total Items = 5
            Item 0 = 20.90%   533 Commands [BillCustomer]
            Item 1 = 19.22%   490 Commands [MakeInvoice]
            Item 2 = 19.41%   495 Commands [MarkAsPreffered]
            Item 3 = 20.98%   535 Commands [SendEmail]
            Item 4 = 19.49%   497 Commands [ShipProduct]

As you can see the total counter is recorded (2550 commands have been executed), but also the number and percent from the total number is recorded for each command.