1
+ use once_cell:: sync:: Lazy ;
1
2
use opentelemetry_api:: global;
2
3
use opentelemetry_api:: trace:: TraceError ;
3
4
use opentelemetry_api:: {
5
+ metrics,
4
6
trace:: { TraceContextExt , Tracer } ,
5
- Key ,
7
+ Context , Key , KeyValue ,
6
8
} ;
7
9
use opentelemetry_otlp:: WithExportConfig ;
10
+ use opentelemetry_sdk:: metrics as sdkmetrics;
8
11
use opentelemetry_sdk:: trace as sdktrace;
9
12
use std:: error:: Error ;
10
13
@@ -19,14 +22,44 @@ fn init_tracer() -> Result<sdktrace::Tracer, TraceError> {
19
22
. install_batch ( opentelemetry_sdk:: runtime:: Tokio )
20
23
}
21
24
25
+ fn init_metrics ( ) -> metrics:: Result < sdkmetrics:: MeterProvider > {
26
+ let export_config = opentelemetry_otlp:: ExportConfig {
27
+ endpoint : "http://localhost:4318/v1/metrics" . to_string ( ) ,
28
+ ..opentelemetry_otlp:: ExportConfig :: default ( )
29
+ } ;
30
+ opentelemetry_otlp:: new_pipeline ( )
31
+ . metrics ( opentelemetry_sdk:: runtime:: Tokio )
32
+ . with_exporter (
33
+ opentelemetry_otlp:: new_exporter ( )
34
+ . http ( )
35
+ . with_export_config ( export_config) ,
36
+ )
37
+ . build ( )
38
+ }
39
+
22
40
const LEMONS_KEY : Key = Key :: from_static_str ( "ex.com/lemons" ) ;
23
41
const ANOTHER_KEY : Key = Key :: from_static_str ( "ex.com/another" ) ;
24
42
43
+ static COMMON_ATTRIBUTES : Lazy < [ KeyValue ; 4 ] > = Lazy :: new ( || {
44
+ [
45
+ LEMONS_KEY . i64 ( 10 ) ,
46
+ KeyValue :: new ( "A" , "1" ) ,
47
+ KeyValue :: new ( "B" , "2" ) ,
48
+ KeyValue :: new ( "C" , "3" ) ,
49
+ ]
50
+ } ) ;
51
+
25
52
#[ tokio:: main]
26
53
async fn main ( ) -> Result < ( ) , Box < dyn Error + Send + Sync + ' static > > {
27
54
let _ = init_tracer ( ) ?;
55
+ let meter_provider = init_metrics ( ) ?;
28
56
29
57
let tracer = global:: tracer ( "ex.com/basic" ) ;
58
+ let meter = global:: meter ( "ex.com/basic" ) ;
59
+
60
+ let histogram = meter. f64_histogram ( "ex.com.two" ) . init ( ) ;
61
+ let cx = Context :: new ( ) ;
62
+ histogram. record ( & cx, 5.5 , COMMON_ATTRIBUTES . as_ref ( ) ) ;
30
63
31
64
tracer. in_span ( "operation" , |cx| {
32
65
let span = cx. span ( ) ;
@@ -44,6 +77,7 @@ async fn main() -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
44
77
} ) ;
45
78
} ) ;
46
79
80
+ meter_provider. shutdown ( ) ?;
47
81
global:: shutdown_tracer_provider ( ) ;
48
82
49
83
Ok ( ( ) )
0 commit comments