1515import logging
1616import psutil
1717
18+ from opencensus .metrics .export .gauge import DerivedDoubleGauge
1819from opencensus .metrics .export .gauge import DerivedLongGauge
1920from opencensus .metrics .export .gauge import Registry
2021from opencensus .metrics .export .metric_producer import MetricProducer
2526# Namespaces used in Azure Monitor
2627AVAILABLE_MEMORY = "\\ Memory\\ Available Bytes"
2728PRIVATE_BYTES = "\\ Process(??APP_WIN32_PROC??)\\ Private Bytes"
29+ PROCESSOR_TIME = "\\ Processor(_Total)\\ % Processor Time"
2830
2931
3032def get_available_memory ():
@@ -75,6 +77,36 @@ def get_process_private_bytes_metric():
7577 return gauge
7678
7779
80+ def get_processor_time ():
81+ cpu_times_percent = psutil .cpu_times_percent ()
82+ return 100 - cpu_times_percent .idle
83+
84+
85+ def get_processor_time_metric ():
86+ """ Returns a derived gauge for the processor time.
87+
88+ Processor time is defined as a float representing the current system
89+ wide CPU utilization minus idle CPU time as a percentage. Idle CPU
90+ time is defined as the time spent doing nothing. Return values range
91+ from 0.0 to 100.0 inclusive.
92+
93+ :rtype: :class:`opencensus.metrics.export.gauge.DerivedDoubleGauge`
94+ :return: The gauge representing the processor time metric
95+ """
96+ gauge = DerivedDoubleGauge (
97+ PROCESSOR_TIME ,
98+ 'Processor time as a percentage' ,
99+ 'percentage' ,
100+ [])
101+ gauge .create_default_time_series (get_processor_time )
102+ # From the psutil docs: the first time this method is called with interval
103+ # = None it will return a meaningless 0.0 value which you are supposed to
104+ # ignore. Call cpu_percent() once so that the subsequent calls from the
105+ # gauge will be meaningful.
106+ psutil .cpu_times_percent ()
107+ return gauge
108+
109+
78110class AzureStandardMetricsProducer (MetricProducer ):
79111 """Implementation of the producer of standard metrics.
80112
@@ -85,6 +117,7 @@ def __init__(self):
85117 self .registry = Registry ()
86118 self .registry .add_gauge (get_available_memory_metric ())
87119 self .registry .add_gauge (get_process_private_bytes_metric ())
120+ self .registry .add_gauge (get_processor_time_metric ())
88121
89122 def get_metrics (self ):
90123 return self .registry .get_metrics ()
0 commit comments