8

Can you open perfmon.exe, clear any current counts and add your custom app counters from C#?

Thinking there about perfmon API but I can't find it.

BartoszKP
  • 34,786
  • 15
  • 102
  • 130
CodingHero
  • 2,865
  • 6
  • 29
  • 42
  • 1
    Have you seen this page: http://www.codeproject.com/Articles/8590/An-Introduction-To-Performance-Counters ? I do agree with Anton Gogolev, performance counters can be a pain, I've seen them get "corrupted" at a dozen servers (not just the counters I was trying to add). – C.Evenhuis Jul 23 '15 at 10:33

2 Answers2

4

Performance Counters are, ahem, not very well suited for tracking application-level metrics.

In Linux/Unix world there's an excellent Graphite and StatsD combination, and we've ported it to .NET: Statsify.

What it allows you is to collect all kinds of metrics from within your application: number of database queries, time it takes to invoke a Web Service, track number of active connections, etc. -- all with simple API like

Stats.Increment("db.query.count");
Anton Gogolev
  • 113,561
  • 39
  • 200
  • 288
0

You can use the PerformanceCounter class, that is int System.System.Diagnostics namespace.

To add your own Category and Counter, you use a code like this:

if (!PerformanceCounterCategory.Exists("AverageCounter64SampleCategory"))
        {

            CounterCreationDataCollection CCDC = new CounterCreationDataCollection();

            // Add the counter.
            CounterCreationData averageCount64 = new CounterCreationData();
            averageCount64.CounterType = PerformanceCounterType.AverageCount64;
            averageCount64.CounterName = "AverageCounter64Sample";
            CCDC.Add(averageCount64);

            // Add the base counter.
            CounterCreationData averageCount64Base = new CounterCreationData();
            averageCount64Base.CounterType = PerformanceCounterType.AverageBase;
            averageCount64Base.CounterName = "AverageCounter64SampleBase";
            CCDC.Add(averageCount64Base);

            // Create the category.
            PerformanceCounterCategory.Create("AverageCounter64SampleCategory",
                "Demonstrates usage of the AverageCounter64 performance counter type.",
                CCDC);

        }

To clear a counter, you can reset RawValue to 0, like this:

var pc = new PerformanceCounter("AverageCounter64SampleCategory",
            "AverageCounter64Sample",
            false);

        pc.RawValue = 0;

These sample codes above I got from this link: system.diagnostics.performancecounter

Hope it helps.

Ricardo Pontual
  • 3,749
  • 3
  • 28
  • 43