-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
64 lines (53 loc) · 2.03 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// NuGet package `System.Diagnostics.PerformanceCounter` have to be installed
// Less functional way there https://gist.github.com/nikvoronin/643b9dc775c648a0397fdf853f70e7b0
// .NET 6
#nullable enable
using System.Diagnostics;
using System.Globalization;
using System.Text;
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
using var writer = new StreamWriter( Console.OpenStandardOutput() );
var categories = PerformanceCounterCategory.GetCategories( Environment.MachineName );
foreach ( var category in categories ) {
writer.WriteLine( $"CATEGORY: {category.CategoryName}" );
string[] instances = ResultOrDefault(
( cat ) => cat.GetInstanceNames(),
Array.Empty<string>(),
category );
// fallthrough if there are no instances
foreach ( var instanceContent in EnumerateInstances( instances, category ) )
writer.Write( instanceContent );
var noInstances = instances.Length == 0;
if ( noInstances ) {
writer.Write( ResultOrDefault(
( cat ) => cat.GetCounters().ToText(),
string.Empty,
category ) );
}
}
writer.WriteLine( "END." );
static IEnumerable<string> EnumerateInstances( IEnumerable<string> instances, PerformanceCounterCategory category )
{
foreach ( var instance in instances )
yield return
$"\tINSTANCE: {instance}\n\t"
+ ResultOrDefault(
( cat ) => cat.GetCounters( instance ),
Array.Empty<PerformanceCounter>(),
category )
.ToText();
}
static TResult ResultOrDefault<TArg, TResult>( Func<TArg, TResult> f, TResult @default, TArg x )
{
try { return f( x ); }
catch { }
return @default;
}
public static class Extensions
{
public static string ToText( this IEnumerable<PerformanceCounter> counters )
=> counters?.Aggregate( new StringBuilder( "\tCOUNTERS:\n" ),
( textBuilder, counter ) => textBuilder.AppendLine( $"\t\t{counter.CounterName}" ) )
.ToString()
?? string.Empty;
}