Skip to content

Commit c9503f1

Browse files
committed
Add a metrics example
1 parent 4c7af79 commit c9503f1

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

examples/metrics/README.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
# Metrics Example
2+
This example shows how to emit OpenTelemetry metrics from MATLAB. It uses all 3 synchronous instruments counter, updowncounter, and histogram.
3+
* At the beginning of the first run, initialization is necessary to create and store a global meter provider.
4+
* The example then enters a loop and at each iteration updates all 3 instruments. The metrics will then be exported periodically at a fixed time interval.
5+
6+
## Running the Example
7+
1. Start an instance of [OpenTelemetry Collector](https://github.com/open-telemetry/opentelemetry-collector).
8+
2. Start MATLAB.
9+
3. Ensure the installation directory of OpenTelemetry-matlab is on the MATLAB path.
10+
4. Run metrics_example.

examples/metrics/metrics_example.m

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
function metrics_example
2+
% This example creates 3 metric instruments including a counter, an
3+
% updowncounter, and a histogram. It then enters a loop and updates the
4+
% value of the instruments at each iteration.
5+
6+
% Copyright 2023 The MathWorks, Inc.
7+
8+
% initialize meter provider during first run
9+
runOnce(@initMetrics);
10+
11+
% create meter and instruments
12+
m = opentelemetry.metrics.getMeter("metrics_example");
13+
c = createCounter(m, "counter");
14+
u = createUpDownCounter(m, "updowncounter");
15+
h = createHistogram(m, "histogram");
16+
iterations = 20; % number of iterations
17+
18+
for i = 1:iterations
19+
c.add(randi(10));
20+
u.add(randi([-10 10]));
21+
h.record(50 + 15*randn); % normal distribution with mean 50 and std 15
22+
pause(5);
23+
end
24+
end
25+
26+
27+
function initMetrics
28+
% set up global MeterProvider
29+
exp = opentelemetry.exporters.otlp.defaultMetricExporter();
30+
reader = opentelemetry.sdk.metrics.PeriodicExportingMetricReader(exp, ...
31+
"Interval", seconds(5), "Timeout", seconds(2.5)); % exports every 5 seconds
32+
% Use custom histogram bins
33+
v = opentelemetry.sdk.metrics.View(InstrumentType="histogram", HistogramBinEdges=0:10:100);
34+
mp = opentelemetry.sdk.metrics.MeterProvider(reader, View=v);
35+
setMeterProvider(mp);
36+
end
37+
38+
% This helper ensures the input function is only run once
39+
function runOnce(fh)
40+
persistent hasrun
41+
if isempty(hasrun)
42+
feval(fh);
43+
hasrun = 1;
44+
end
45+
end

0 commit comments

Comments
 (0)
close