matlab-instrument-opentelemetry-tracing
>
git clone --depth 1 https://github.com/matlab/matlab-agentic-toolkit /tmp/matlab-instrument-opentelemetry-tracing && cp -r /tmp/matlab-instrument-opentelemetry-tracing/skills-catalog/matlab-software-development/matlab-instrument-opentelemetry-tracing ~/.claude/skills/matlab-instrument-opentelemetry-tracingSKILL.md
# Instrument MATLAB Code with OpenTelemetry Tracing
Add OpenTelemetry tracing spans to MATLAB functions with correct implicit context
propagation, RAII lifecycle, and semantic conventions.
## Prerequisites
The [OpenTelemetry-MATLAB](https://www.mathworks.com/matlabcentral/fileexchange/130979-opentelemetry-matlab) package (Version 1.11.0 or newer) must be installed. It provides the `opentelemetry.trace.*` namespace used throughout this skill. Requires MATLAB R2022b or newer.
## Key Functions
| Function | Purpose | Toolbox | Available From |
|----------|---------|---------|----------------|
| `opentelemetry.trace.getTracer` | Obtain a tracer instance by name | OpenTelemetry-MATLAB | R2022b |
| `startSpan` | Create a new span from a tracer | OpenTelemetry-MATLAB | R2022b |
| `makeCurrent` | Set span as current context (enables implicit parent-child) | OpenTelemetry-MATLAB | R2022b |
| `setAttributes` | Attach key-value metadata to a span | OpenTelemetry-MATLAB | R2022b |
| `setStatus` | Mark span as "Ok" or "Error" | OpenTelemetry-MATLAB | R2022b |
| `recordException` | Record an MException on a span | OpenTelemetry-MATLAB | R2022b |
| `addEvent` | Record a timestamped event within a span | OpenTelemetry-MATLAB | R2022b |
| `endSpan` | End a span mid-function (loops only) | OpenTelemetry-MATLAB | R2022b |
## MATLAB API Differences
The MATLAB OpenTelemetry API differs slightly from C++, Java, and Python implementations. Do not rely on general OTel knowledge from other languages — when unsure about a function, use `help opentelemetry.trace.Span` or similar to check what exists. Common traps:
- `setAttribute` (singular) does not exist — use `setAttributes` (plural)
- `opentelemetry.trace.StatusCode.Ok` / `StatusCode.Error` enums do not exist — pass the strings `"Ok"` or `"Error"` directly to `setStatus`
## When to Use
- User asks to add tracing or spans to MATLAB code
- User asks to instrument code with OpenTelemetry
- User asks to add observability and tracing is part of the request
- User wants parent-child span relationships across functions
## When NOT to Use
- User wants metrics only (counters, histograms, gauges) — no tracing skill needed
- User wants logging only (structured log records) — no tracing skill needed
- User wants to configure the TracerProvider/SDK (exporters, samplers, resource) — that belongs in a separate setup script
- User wants to propagate context across network boundaries (inject/extract into HTTP headers)
- User wants to instrument inside `parfor` loops — OTel context is not thread-safe in MATLAB
## Absolute Rules
These rules override all other considerations. Violating any of them produces incorrect instrumentation.
### 1. Never modify function signatures
Instrumentation must be invisible to callers. Never add parameters (tracer, context, span) to a function. Never change return values. Each function obtains its own tracer internally:
```matlab
tr = opentelemetry.trace.getTracer("tracer_name");
```
This is a cheap lookup from the global provider, not a resource allocation.
### 2. Spans are RAII — never call `endSpan` at function exit
The MATLAB Span object holds a C++ shared pointer. When the span variable goes out of scope (function returns, error thrown), the C++ destructor automatically ends the span. Only call `endSpan` when you need to end a span **mid-function** before the variable naturally goes out of scope.
### 3. Scope is RAII — never call `clear(scope)` at function exit
The Scope object returned by `makeCurrent` restores the previous context when it goes out of scope. Assign it to a variable to control its lifetime. The `%#ok<NASGU>` pragma suppresses the "unused variable" warning because the variable's lifetime is its purpose, not its value. Exception: inside loops, `clear` is required to restore the parent context before the next iteration (see loop pattern).
### 4. Always call `makeCurrent` on every span
Every span must be made current so child spans created in called functions automatically become children. Without `makeCurrent`, child spans become orphaned root spans.
### 5. Never pass explicit "Context" to `startSpan`
When `makeCurrent` is used consistently, `startSpan` automatically picks up the current span as parent. Passing `"Context"` explicitly is redundant and error-prone. The only exception is when creating a span that must be a child of a *different* span than the current one (rare).
### 6. Always set span status
Every span must have its status set before it ends:
- `setStatus(span, "Ok")` on the success path
- `setStatus(span, "Error", message)` on the failure path
A span without explicit status is ambiguous in trace viewers.
### 7. Use `getTracer` directly
```matlab
tr = opentelemetry.trace.getTracer("tracer_name");
```
Never use `opentelemetry.sdk.trace.TracerProvider()` or `opentelemetry.trace.Provider.getTracerProvider()` followed by `getTracer`. The one-liner above is the correct entry point.
### 8. Use snake_case attribute names with meaningful domain nouns
All attribute names must be lowercase, dot-separated, and use snake_case within each component. The namespace (left of the dot) must be a meaningful domain noun — not a generic word like "total", "numeric", or "count". See the Semantic Conventions section below for the full pattern and examples.
## Workflow
### Step 1: Analyze the code
Identify:
- Entry-point function (top-level function the user calls)
- Sub-functions and local functions that represent distinct units of work
- I/O operations (file read/write, network calls, database)
- Error-prone sections (file I/O, external systems, parsing)
- Computationally significant operations worth tracking
### Step 2: Choose a tracer name
Derive from the file name or containing package:
- `processSensorData.m` → `"processSensorData"`
- `+mypackage/analyze.m` → `"mypackage"`
All functions in the same workflow should share the same tracer name.
### Step 3: Instrument each function
Apply the core>
Import recorded driving sensor data (GPS, camera, lidar, actor tracks, lanes) into scenariobuilder.* objects (GPSData, CameraData, LidarData, ActorTrackData, Trajectory, laneData) and run preprocessing — synchronize, offset correction, crop, normalizeTimestamps, convertTimestamps. Also: compute actor tracks from lidar when no annotations exist, attach camera/lidar mounting + intrinsics, export to MAT/workspace/timetable/script. Use for raw driving dataset files (KITTI, nuScenes, Waymo, Pandaset, ROS/ROS2 bags, .mat, .csv, .mp4) or driving/vehicle/sensor logs that need wrapping. drivingLogAnalyzer (DLA) is OPT-IN ONLY — invoke only on explicit user request ('DLA', 'open in DLA', 'inspect/explore/analyze the recording') or reported sensor problem (sync drift, timestamp mismatch, overlay misalignment). NEVER auto-launch DLA after wrapping (Rule 0). For 'build scenario / export to RoadRunner / drivingScenario / OpenSCENARIO / Unreal / simulate', hand off to matlab-scenario-builder.
Generate driving scenes, scenarios, road surfaces, and 3D content from already-wrapped scenariobuilder.* sensor data (GPS, camera, lidar, actor tracks) using Scenario Builder for Automated Driving Toolbox. Use to BUILD, EXPORT, or AUGMENT a virtual scenario/scene/map: ego or actor trajectories, trajectory smoothing, OpenCRG road-surface extraction, 3D asset generation, static-object placement, point-cloud georeferencing + elevation, lane-based ego localization, sensor-fusion tracking, scenario-event extraction (cut-ins, hard brakes, near-misses, ADAS disengagements), or export to RoadRunner, drivingScenario, OpenDRIVE, OpenCRG, OpenSCENARIO, or Unreal Engine. Also: log-to-scenario, scenario harvesting, accident/near-miss reconstruction, SOTIF (ISO 21448) and ISO 26262 scenario coverage, USGS-aerial-lidar scene augmentation, traffic-sign placement from camera+lidar logs. NOT for raw-data import or multi-sensor sync/crop/offset/timestamp normalization — route those to matlab-driving-data-importer.
>
>
>
>
Build, modify, and diagram SimBiology models — API reference, helper functions, and layout patterns. Use when constructing or editing models programmatically or visually.