Skip to main content
ClaudeWave
ES, Spanish
Skill1.2k estrellas del repoactualizado 6d ago

matlab-instrument-opentelemetry-tracing

>

Instalar en Claude Code
Copiar
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-tracing
Después abre una sesión nueva de Claude Code; el skill carga automáticamente.

SKILL.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
matlab-access-datafeedSkill

>

matlab-analyze-ams-waveformSkill

Analyze AMS waveform data using Mixed-Signal Blockset utilities: phase noise measurement, clock jitter, anti-aliased resampling, timing measurements, lock time, INL/DNL, ADC/DAC calibration, HSpice import. Use when analyzing time-domain voltage from PLL/VCO/clock simulations, measuring phase noise from variable-step solver output, computing jitter, or resampling non-uniform data.

matlab-analyze-dataSkill

Analyze data using MATLAB. Use when the task involves tables, timetables, time-series data, numeric arrays, sensor matrices, or gridded data — including but not limited to exploring, filtering, sorting, cleaning, transforming, aggregating, smoothing, padding, trimming, and answering questions about data. MATLAB provides extensive, easy-to-use built-in functions for these workflows with no additional products required.

matlab-analyze-dependenciesSkill

Analyze the effective toolbox file set to produce a Dependency Manifest — classify all transitive dependencies as included, product, add-on, or external-unresolved, then present resolution options with tradeoffs. Use after matlab-define-toolbox-api when the spec is approved.

matlab-analyze-emSkill

S-parameters, insertion loss, fields, currents, mesh control, and solver selection for RF PCB performance validation. TRIGGER: user asks to compute S-parameters, analyze insertion/return loss, extract fields or currents, compare MoM vs FEM, or control mesh for any RF PCB component. Invoke BEFORE writing sparameters() or solver code — API is non-obvious. SKIP: designing or creating components (use the specific matlab-design-pcb-* skill), material/stackup setup only (use matlab-manage-pcb-material), optimization sweeps (use matlab-optimize-pcb-design), PDN/IR-drop analysis (use matlab-analyze-pcb-pdn).

matlab-analyze-installed-antennaSkill

Analyze antennas installed on electrically large conducting platforms using MATLAB Antenna Toolbox. Loads platform geometry from STL/STEP/IGES, installs antenna elements, selects electromagnetic solvers (MoM-PO, FMM, MoM), and computes patterns, impedance, coupling, and efficiency. Use when the user wants to model an antenna on a vehicle, aircraft, ship, satellite, or other large structure.

matlab-analyze-pcb-pdnSkill

PDN DC voltage/current analysis, IR drop, design rule checking, and multi-net batch analysis on imported PCB layouts. TRIGGER: user asks about power integrity, PDN analysis, IR drop, voltage distribution, current density, power nets, or design rule checking on a PCB. Invoke BEFORE writing code — the PDN API chain is specialized and non-obvious. SKIP: importing a PCB file (use matlab-read-pcb-layout), EM field/S-parameter extraction (use matlab-analyze-em), material/stackup setup only (use matlab-manage-pcb-material), transmission line design (use matlab-design-pcb-txline).

matlab-analyze-rcsSkill

Calculate and visualize monostatic and bistatic radar cross section (RCS) using MATLAB Antenna Toolbox. Computes RCS of platforms, antennas, and arrays with PO, MoM, and FMM solvers, supporting HH/VV/HV/VH polarization, GPU acceleration, and near-field observation. Use when the user wants to compute, plot, or analyze radar cross section.