当前位置:网站首页>. net core cross platform resource monitoring library and dotnet tool

. net core cross platform resource monitoring library and dotnet tool

2020-11-08 19:54:00 A fool is a good worker

brief introduction

CZGL.SystemInfo It's a support Windows and Linux And other platforms can obtain the machine hardware information 、 Collect machine resource information 、 A library that monitors process resources .

Without introducing additional dependencies , Use .NET Runtime Of itself API, Or get information through calculation , Provides high performance computing and caching , Improve performance , Also provide dotnet tool Tools , Use at the terminal through the command line .

Because this library is completely rewritten , So it's the same as the old version of API Completely different , Old version address :

The old version GitHub: https://github.com/whuanle/CZGL.SystemInfo/tree/0.1

The old version of the tutorial : https://www.cnblogs.com/whuanle/p/12435413.html

Nuget Search for CZGL.SystemInfo You can install , Version is 1.0 .

Every property and method in the class library , I've added nice notes and return Example .

CZGL.SystemInfo.Linux Optimize part of the code , The rest remains unchanged .

Windows have access to System.Diagnostics.PerformanceCounter 、System.Management.ManagementObjectSearcher Get the performance calculator and the machine respectively CPU model 、 Disk serial number and other information .

Platforms are different and hard to unify , So, if you want to get some hardware model serialization , Resource information to obtain process information , These related system call requirements API Or use the command line , You need to customize .

dotnet tool Experience

So far a simple dotnet Tools , There is no need to SDK,runtime You can use .

Installation command :

dotnet tool install --global csys
# or
dotnet tool install --global csys --version 1.0.3
You can invoke the tool using the following command: csys
Tool 'csys' (version '1.0.2') was successfully installed.

If in Linux Next , install , You also need to set environment variables :

export PATH="$PATH:/home/{ Your username }/.dotnet/tools"

After installation , Enter the command to enter the widget :

csys
 Please enter a command 
+------- Command Reference ------------------------------+
| 1.  Input  netinfo  Check the network details                   |
| 2.  Input  nett  Monitoring network traffic                      |
| 3.  Input  test , Check what the current operating system is not compatible with  API    |
| 4.  Input  ps  View process information                        |
+---------------------------------------------+

notes : Need to use super administrator to start program , Can be used ps function ;

Moving graph :

csys

Gadgets don't have many functions , If you are interested, you can download Nuget package , There are more functions in it .

CZGL.SystemInfo

CZGL.SystemInfo There are currently four categories :DiskInfo、NetworkInfo、ProcessInfo、SystemPlatformInfo, Let's talk about each of them .

To avoid wasting resources ,DiskInfo、NetworkInfo、ProcessInfo Some properties use lazy loading , Don't use this API Under the circumstances , No need to consume performance .

Install-Package CZGL.SystemInfo -Version 1.0.1

SystemPlatformInfo

Static class , Ability to access operating environment information and limited hardware information , All the information is confirmed before the program starts .

Its API Examples of the data described and obtained are as follows :

attribute explain Windows Example Linux Example
FrameworkDescription Frame platform (.NET Core、Mono etc. ) Information .NET Core 3.1.9 .NET Core 3.1.9
FrameworkVersion Runtime information version 3.1.9 3.1.9
OSArchitecture Operating system platform architecture X64 X64
OSPlatformID Get the type of operating system Win32NT Unix
OSVersion Operating system kernel version Microsoft Windows NT 6.2.9200.0 Unix 4.4.0.19041
OSDescription Version Description of the operating system Microsoft Windows 10.0.19041 Linux 4.4.0-19041-Microsoft #488-Microsoft Mon Sep 01 13:43:00 PST 2020
ProcessArchitecture The architecture of this process X64 X64
ProcessorCount The number of processors on the current computer 8 8
MachineName Computer name dell-PC dell-PC
UserName The name of the user currently logged in to this system dell dell
UserDomainName User network domain name dell-PC dell-PC
IsUserInteractive Whether to run in interactive mode True True
GetLogicalDrives System disk and partition list D:, E:, F:, G:, H:, J:, X:|/, /dev, /sys, /proc, /dev/pts, /run, /run/lock, /run/shm
SystemDirectory System root full path X:\WINDOWS\system32
MemoryPageSize The number of bytes per page of the operating system memory page 4096 4096

SystemPlatformInfo Of API There will be no cross platform incompatibility issues , You can use it boldly .

Effect demonstration :

 System platform information :

 Operational framework     :    .NET Core 3.1.0
 operating system     :    Microsoft Windows 10.0.17763
 Operating system version     :    Microsoft Windows NT 6.2.9200.0
 The platform architecture     :    X64
 Machine name     :    aaaa-PC
 Current associated user name     :    aaa
 User network domain name     :    aaa-PC
 The system has been running for ( millisecond )    :    3227500
Web Core framework version of the program     :    3.1.0
 Whether to run in interactive mode     :    True
 Partition disk     :    D:\, E:\, F:\, G:\, H:\, X:\
 System catalog     :    X:\windows\system32
 The current process has used physical memory     :    20020
 The current process has consumed CPU Time     :    328.125
 Memory used by all processes in the system     :    System.Collections.Generic.KeyValuePair`2[System.String,System.Int64][]
 The system has used memory     :    5988340
VisualStudioVersion    :    16.0

ProcessInfo

Need to use super administrator to start program , To use this function ;

Record the resource data of the operating system at a certain time . this API There are some points to pay attention to when using , Comparing monitoring and refreshing information consumes some performance resources .

Through two static methods , You can get the process list of the system :

Dictionary<int,string> value = ProcessInfo.GetProcessList();
ProcessInfo[] value = ProcessInfo.GetProcesses();

Or through a specified process ID obtain :

ProcessInfo value = ProcessInfo.GetProcess(666);

get ProcessInfo After the object , You have to use Refresh() Method refresh 、 Intercepts the current process status information , To get information .

Such as :

ProcessInfo thisProcess = ProcessInfo.GetCurrentProcess();	//  Get the... Of the current process  ProcessInfo  object 
thisProcess.Refresh();

Only if you use .Refresh() when , Will start to initialize , And generate the corresponding information .

The information obtained is not dynamic , And save the process status data of a node at any time , So if you need to update dynamically , You need to do it again .Refresh() Method .

ProcessInfo Can get the amount of memory used by the process and CPU Time , But we can't get the physical memory usage of this process and CPU Usage rate . If you want to get the usage ratio , Need to call the operating system API, Or use other libraries of the operating system , Such as Windows Of WMI.

If you want to get a process of CPU The proportion of consumption , You can use static methods :

decimal value = ProcessInfo.GetCpuPercentage(666);

about 2 Seconds will refresh once , So don't wait for this all the time API Return the data , It is suitable to be calculated separately , Not suitable for integration with other data . this API Monitored CPU The percentage is not very accurate .

CPU It's really hard to find , You can look at the paper :

https://www.semanticscholar.org/paper/Late-Breaking%3A-Measuring-Processor-Utilization-in-Friedman/d7e312e32cd6bb6cac4531389c5cc7c80481b9b5?p2df

Keep refreshing CPU data :

            while (true)
            {
                var tmp = Convert.ToInt32(Console.ReadLine());
                var process = ProcessInfo.GetProcess(tmp);
                process.Refresh();                          //  Refresh process data 
                var cpu = ProcessInfo.GetCpuPercentage(process.ProcessId);
                Console.WriteLine($" process  {process.ProcessName} CPU : {cpu * 100}%");
            }

Memory monitoring

PhysicalUsedMemory Property indicates the current size of the pageable system memory used by the process ( In bytes ). System memory is the physical memory used by the operating system , Divided into paged and non paged pools . When non pageable memory is not in use , It can be transferred to a virtual memory paging file on disk .

The attribute name explain Example
PhysicalUsedMemory Number of bytes of physical memory used 17498112

NetworkInfo

NetworkInfo Be able to obtain network interface information .

NetworkInfo.GetNetworkInfo() Access to the preferred network device that your computer is currently connected to the Internet .

If you use wifi, What you get is a wireless network card ; Use the Internet cable to access the Internet , What you get is an Ethernet card .

API Examples of use :

            var info = NetworkInfo.GetNetworkInfo();
            Console.WriteLine("\r\n+++++++++++");
            Console.WriteLine($"     The network card name     {info.Name}");
            Console.WriteLine($"     Network link speed  {info.Speed / 1000 / 1000} Mbps");
            Console.WriteLine($"    Ipv6       {info.AddressIpv6.ToString()}");
            Console.WriteLine($"    Ipv4       {info.AddressIpv4.ToString()}");
            Console.WriteLine($"    DNS        {string.Join(',', info.DNSAddresses.Select(x => x.ToString()).ToArray())}");
            Console.WriteLine($"     Uplink traffic statistics  {info.SendLength / 1024 / 1024} MB");
            Console.WriteLine($"     Downlink traffic statistics  {info.ReceivedLength / 1024 / 1024} MB");
            Console.WriteLine($"     Network type      {info.NetworkType}");
            Console.WriteLine($"     network card MAC     {info.Mac}");
            Console.WriteLine($"     Network card information      {info.Trademark}");

Status Property can get the status of this network card , The enumeration is as follows :

Dormant 5 The network interface is not in the state of transmitting packets ; It's waiting for external events .
Down 2 The network interface is unable to transmit packets .
LowerLayerDown 7 The network interface is unable to transmit packets , Because it runs on one or more other interfaces , And these “ low ” At least one of the interfaces is closed .
NotPresent 6 Due to the lack of components ( Usually hardware components ), The network interface is unable to transmit packets .
Testing 3 The network interface is running tests .
Unknown 4 The state of the network interface is unknown .
Up 1 Network interface is running , Can transmit packets .

NetworkType You can get the interface type of network card , There are many enumerations , Please refer to :

https://docs.microsoft.com/zh-cn/dotnet/api/system.net.networkinformation.networkinterfacetype?view=netcore-3.1

Usually , Monitoring networks , Check whether the network is unblocked , Second, monitoring traffic .

NetworkInfo.IsAvailable Static properties can check whether the current machine can connect to the Internet . The qualified network card must be able to run and transmit packets , And it can't be a local loopback address . If you're an intranet , You may not need this API, You can do it yourself ping Other machines in Intranet , Make sure the network is clear .

How to use real-time monitoring network speed :

            var info = NetworkInfo.GetNetworkInfo();
                while (true)
                {
                    var tmp = info.GetInternetSpeed(1000);
                    Console.WriteLine($" Internet upload speed :{tmp.Send / 1024} kb/s");
                    Console.WriteLine($" Network download speed :{tmp.Received / 1024} kb/s");
                    Thread.Sleep(500);
                }

(int Received, int Send) GetInternetSpeed(int Milliseconds) Method can monitor the amount of data transmitted over the network , The time is usually set to 1000 ms.

Received  It's download traffic 
Send      It's upload traffic 

Generally speaking , The computer has only one network card connected to the Internet , So you can use :

static (int Received, int send) GetNowInternetSpeed(int Milliseconds)

It will automatically find the network card that the computer is using to access the Internet , And record the flow size .

There's another. Speed attribute , You can query the maximum support rate of the network card .

If it is -1, It means that the link speed of this network card cannot be obtained ; for example 270_000_000 Said is 270MB( Generally refer to 300M network card ) Link speed . Gigabit network card is 1000_000_000(1000M).

Other API No introduction .

Direct reflection view :

NetworkInterface System.Net.NetworkInformation.SystemNetworkInterface
Id {43538D18-BB0E-4CE2-8F66-613FAC9467BD}
Mac E09D3116D014
Name WLAN
Trademark Intel(R) Centrino(R) Advanced-N 6205
PhysicalMac E09D3116D014
Status Up
NetworkType Wireless80211
Statistics System.Net.NetworkInformation.SystemIPInterfaceStatistics
Ipv4Statistics System.Net.NetworkInformation.SystemIPv4InterfaceStatistics
ReceivedLength 103449771
ReceivedLengthIpv4 103449771
SendLength 23753785
SendLengthIpv4 23753785
IsAvailable True
Speed 300000000
IsSupportIpv4 True
IsSupportIpv6 True
DnsSuffix
DNSAddresses System.Net.NetworkInformation.InternalIPAddressCollection
UnicastIPAddressInformationCollection System.Net.NetworkInformation.UnicastIPAddressInformationCollection
AddressIpv6 fe90::adbb:6aa1:2b1f:ae9b%11
AddressIpv4 192.168.3.3
GetPhysicalMac E69D3116D514

Be careful , Because there are some API ,Linux The environment is quite different , It is recommended to use csys Gadgets test command , Check out what API Can be here Linux Use in the environment .

DiskInfo

DiskInfo There is not much information available .

You can use the static method to get all the disk's DiskInfo object :

DiskInfo.GetDisks()

Look at it directly :

DriveInfo F:\
Id F:\
Name F:\
DriveType Fixed
FileSystem NTFS
FreeSpace 76498378752
TotalSize 112718770176
UsedSize 36220391424

Linux

Nuget Search for CZGL.SystemInfo.Linux install .

In this library ,Linux Resource information includes Process metering , Memory metering ,CPU metering , Virtual memory metering , Various processes run information measurement .

By instantiating DynamicInfo To get .

Yes 5 Objects are used to map the corresponding information .

Tasks: Used to count the number of processes , The number of processes in different states .

CpuState:CPU usage ,CPU Various load information .

Mem: Physical memory and cache usage .

Swap: Virtual memory usage .

PidInfo: Information about the running resources of a process .

They all have one IsSuccess attribute , It is used to judge whether it can be obtained normally Linux Information about .

Instantiate to get the object

            DynamicInfo info = new DynamicInfo();

Use it directly

The corresponding object can be obtained through the method .

            var item = info.GetTasks();
            Console.WriteLine(" There are processes in the system     :" + item.Total);
            Console.WriteLine(" Number of running processes     :" + item.Running);
            Console.WriteLine("   process Id   Process name    Users      Optimization level    High and low priority    Virtual memory     Physical memory     Shared memory   Process status    Occupancy system CPU(%)    Take up memory (%d) ");

Output

 Process statistics :

Total    :    93
Running    :    1
Sleeping    :    59
Stopped    :    0
Zombie    :    0


CPU Resource Statistics :

UserSpace    :    1
Sysctl    :    0.6
NI    :    0
Idolt    :    98.3
WaitIO    :    0.1
HardwareIRQ    :    0
SoftwareInterrupts    :    0


 Memory statistics :

Total    :    1009048
Used    :    334040
Free    :    85408
Buffers    :    589600
CanUsed    :    675008


 Get virtual memory statistics :

Total    :    0
Used    :    0
Free    :    0
AvailMem    :    505744

版权声明
本文为[A fool is a good worker]所创,转载请带上原文链接,感谢