|
| 1 | +function yf = logs_example |
| 2 | +% This example creates and emits logs from MATLAB code that fits a line |
| 3 | +% through a cluster of data points. It create a log record for each |
| 4 | +% function call, and it also captures the parameters of the best fit line. |
| 5 | + |
| 6 | +% Copyright 2024 The MathWorks, Inc. |
| 7 | + |
| 8 | +% initialize logging during first run |
| 9 | +runOnce(@initLogger); |
| 10 | + |
| 11 | +% create a logger and start emitting logs |
| 12 | +lg = opentelemetry.logs.getLogger("logs_example"); |
| 13 | +info(lg, "logs_example"); |
| 14 | + |
| 15 | +[x, y] = generate_data(); |
| 16 | +yf = best_fit_line(x,y); |
| 17 | +end |
| 18 | + |
| 19 | +function [x, y] = generate_data |
| 20 | +% generate some random data |
| 21 | +lg = opentelemetry.logs.getLogger("logs_example"); |
| 22 | +info(lg, "generate_data"); |
| 23 | + |
| 24 | +a = 1.5; |
| 25 | +b = 0.8; |
| 26 | +sigma = 5; |
| 27 | +x = 1:100; |
| 28 | +y = a * x + b + sigma * randn(1, 100); |
| 29 | +end |
| 30 | + |
| 31 | +function yf = best_fit_line(x, y) |
| 32 | +% fit a line through points defined by inputs x and y |
| 33 | +lg = opentelemetry.logs.getLogger("logs_example"); |
| 34 | +info(lg, "best_fit_line"); |
| 35 | + |
| 36 | +coefs = polyfit(x, y, 1); |
| 37 | + |
| 38 | +% capture the coefficients |
| 39 | +info(lg, coefs); |
| 40 | + |
| 41 | +yf = polyval(coefs , x); |
| 42 | +end |
| 43 | + |
| 44 | +function initLogger |
| 45 | +% set up global LoggerProvider |
| 46 | +resource = dictionary("service.name", "OpenTelemetry-Matlab_examples"); |
| 47 | +lp = opentelemetry.sdk.logs.LoggerProvider(... |
| 48 | + opentelemetry.sdk.logs.SimpleLogRecordProcessor, Resource=resource); |
| 49 | +setLoggerProvider(lp); |
| 50 | +end |
| 51 | + |
| 52 | +% This helper ensures the input function is only run once |
| 53 | +function runOnce(fh) |
| 54 | +persistent hasrun |
| 55 | +if isempty(hasrun) |
| 56 | + feval(fh); |
| 57 | + hasrun = 1; |
| 58 | +end |
| 59 | +end |
0 commit comments