1+ from opencensus .ext .azure import metrics_exporter
2+ from opencensus .stats import aggregation as aggregation_module
3+ from opencensus .stats import measure as measure_module
4+ from opencensus .stats import stats as stats_module
5+ from opencensus .stats import view as view_module
6+ from opencensus .tags import tag_map as tag_map_module
7+ import os
8+
9+ class MetricLogger :
10+ def __init__ (self , metric_name :str , custom_dimension_keys :list = []):
11+ self .custom_dimension_keys = custom_dimension_keys
12+ stats = stats_module .stats
13+ view_manager = stats .view_manager
14+ stats_recorder = stats .stats_recorder
15+ self .metric_measure_module = measure_module .MeasureFloat ("Metric" , "" , "" )
16+
17+ request_view = view_module .View (metric_name , "" ,
18+ self .custom_dimension_keys ,
19+ self .metric_measure_module ,
20+ aggregation_module .LastValueAggregation ())
21+
22+ exporter = metrics_exporter .new_metrics_exporter (connection_string = f'InstrumentationKey={ os .environ .get ("APPINSIGHTS_INSTRUMENTATION_KEY" )} ' )
23+
24+ view_manager .register_exporter (exporter )
25+
26+ view_manager .register_view (request_view )
27+ self .mmap = stats_recorder .new_measurement_map ()
28+ self .tmap = tag_map_module .TagMap ()
29+
30+ def insert_customdimension (self , key : str , value : str ):
31+ if key not in self .custom_dimension_keys :
32+ self .custom_dimension_keys .append (key )
33+
34+ self .tmap .insert (key , value )
35+
36+ def set_customdimension (self , custom_dimension : dict ):
37+ for key , value in custom_dimension .items ():
38+ self .insert_customdimension (key , str (value ))
39+
40+ def set_metric_value (self , value :float ):
41+ self .mmap .measure_float_put (self .metric_measure_module , value )
42+ self .mmap .record (self .tmap )
0 commit comments