> ## Documentation Index
> Fetch the complete documentation index at: https://docs.localdev.build/llms.txt
> Use this file to discover all available pages before exploring further.

# Instrumenting your services

> Send logs, metrics and traces from Go, Python and Node.js

Localdev shows the logs, metrics and traces your services send over OpenTelemetry (OTLP). This page shows how to set up the OpenTelemetry SDK in Go, Python and Node.js. Each example sends logs linked to traces, traces, and a `jobs.done` metric.

## What Localdev configures for you

Localdev sets these variables for every service:

```
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4998
OTEL_EXPORTER_OTLP_PROTOCOL=grpc
OTEL_EXPORTER_OTLP_INSECURE=true
OTEL_RESOURCE_ATTRIBUTES=service.name=<service name>
```

OpenTelemetry SDKs read them, so there's no endpoint to set in your code. Each service's telemetry is labelled with its name from the Projectfile. To change these values, see [Environment variables](https://docs.localdev.build/configuration/environment-variables.md#variables-localdev-sets).

The collector receives OTLP gRPC on port 4998 and OTLP HTTP on port 4999. Go, Python and Node.js all work with the gRPC default. Node.js's SDK defaults to HTTP, but follows `OTEL_EXPORTER_OTLP_PROTOCOL`.

## Before you start

* **Send metrics more often.** SDKs export metrics every 60 seconds by default. For local work, 5 seconds is more useful:

  ```yaml theme={null}
  env:
      OTEL_METRIC_EXPORT_INTERVAL: "5000"
  ```

* **Link logs to traces.** A log is linked to a trace when it's written while a span is active. In Go, pass the span's context to the logger. In Python and Node.js, auto-instrumentation does it for you.

* **Flush on the way out.** Localdev stops services with SIGTERM. Shut the SDK down when your service exits, so the last batch of telemetry still arrives.

## Go

Tested with `go.opentelemetry.io/otel` 1.47.0 and `go.opentelemetry.io/contrib/bridges/otelslog` 0.21.0.

Save this as `main.go`:

```go main.go theme={null}
package main

import (
	"context"
	"log/slog"
	"os/signal"
	"syscall"
	"time"

	"go.opentelemetry.io/contrib/bridges/otelslog"
	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc"
	"go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc"
	"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
	"go.opentelemetry.io/otel/log/global"
	"go.opentelemetry.io/otel/metric"
	sdklog "go.opentelemetry.io/otel/sdk/log"
	sdkmetric "go.opentelemetry.io/otel/sdk/metric"
	sdktrace "go.opentelemetry.io/otel/sdk/trace"
)

func main() {
	// Localdev stops services with SIGTERM: flush the telemetry on the way out.
	ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
	defer stop()

	// The exporters read OTEL_EXPORTER_OTLP_ENDPOINT and OTEL_EXPORTER_OTLP_INSECURE, and the SDK
	// reads OTEL_RESOURCE_ATTRIBUTES (the service name). Localdev sets all three.
	traceExporter, err := otlptracegrpc.New(ctx)
	if err != nil {
		panic(err)
	}
	tracerProvider := sdktrace.NewTracerProvider(sdktrace.WithBatcher(traceExporter))
	defer tracerProvider.Shutdown(context.Background())
	otel.SetTracerProvider(tracerProvider)

	metricExporter, err := otlpmetricgrpc.New(ctx)
	if err != nil {
		panic(err)
	}
	meterProvider := sdkmetric.NewMeterProvider(sdkmetric.WithReader(sdkmetric.NewPeriodicReader(metricExporter)))
	defer meterProvider.Shutdown(context.Background())
	otel.SetMeterProvider(meterProvider)

	logExporter, err := otlploggrpc.New(ctx)
	if err != nil {
		panic(err)
	}
	loggerProvider := sdklog.NewLoggerProvider(sdklog.WithProcessor(sdklog.NewBatchProcessor(logExporter)))
	defer loggerProvider.Shutdown(context.Background())
	global.SetLoggerProvider(loggerProvider)

	logger := otelslog.NewLogger("demo")
	tracer := otel.Tracer("demo")
	jobs, err := otel.Meter("demo").Int64Counter("jobs.done", metric.WithUnit("{job}"), metric.WithDescription("Finished jobs"))
	if err != nil {
		panic(err)
	}

	ticker := time.NewTicker(2 * time.Second)
	defer ticker.Stop()
	for {
		select {
		case <-ctx.Done():
			return
		case <-ticker.C:
			jobCtx, span := tracer.Start(ctx, "process-job")
			// Pass the context, so the log line is linked to the span.
			logger.InfoContext(jobCtx, "job finished", slog.String("queue", "default"))
			jobs.Add(jobCtx, 1)
			span.End()
		}
	}
}
```

Build it:

```sh theme={null}
go mod init demo
go mod tidy
go build -o main .
```

Then add it to the Projectfile:

```yaml theme={null}
services:
    demo:
        command: ./main
```

The Go SDK doesn't link logs to traces by itself. Use the `…Context` logging methods (`InfoContext`, `ErrorContext`, …) with the span's context, as above.

## Python

Tested with Python 3.13, `opentelemetry-sdk` 1.45.2 and `opentelemetry-distro` 0.66b2.

Install the packages into a virtual environment:

```sh theme={null}
uv venv --python 3.13 .venv
uv pip install --python .venv/bin/python opentelemetry-distro opentelemetry-exporter-otlp
```

Save this as `app.py`:

```python app.py theme={null}
import logging, time
from opentelemetry import metrics, trace

logging.basicConfig(level=logging.INFO)
log = logging.getLogger("demo")
tracer = trace.get_tracer("demo")
jobs = metrics.get_meter("demo").create_counter("jobs.done", unit="{job}", description="Finished jobs")

while True:
    with tracer.start_as_current_span("process-job"):
        log.info("job finished")
        jobs.add(1)
    time.sleep(2)
```

Run it through `opentelemetry-instrument`, which sets up the SDK before your code starts:

```yaml theme={null}
services:
    demo:
        command: .venv/bin/opentelemetry-instrument .venv/bin/python app.py
        env:
            OTEL_LOGS_EXPORTER: otlp
            OTEL_PYTHON_LOGGING_AUTO_INSTRUMENTATION_ENABLED: "true"
```

Without these two variables, Python sends traces and metrics, but not logs.

## Node.js

Tested with Node.js 24.4 and `@opentelemetry/auto-instrumentations-node` 0.83.1.

Install the packages:

```sh theme={null}
npm install @opentelemetry/api @opentelemetry/auto-instrumentations-node pino
```

Save this as `app.js`:

```js app.js theme={null}
const { trace, metrics } = require('@opentelemetry/api');
const logger = require('pino')();

const tracer = trace.getTracer('demo');
const jobs = metrics.getMeter('demo').createCounter('jobs.done', { unit: '{job}', description: 'Finished jobs' });

setInterval(() => {
  tracer.startActiveSpan('process-job', (span) => {
    logger.info('job finished');
    jobs.add(1);
    span.end();
  });
}, 2000);
```

Load the auto-instrumentation with `--require` in the command, and turn on the three exporters:

```yaml theme={null}
env:
    OTEL_TRACES_EXPORTER: otlp
    OTEL_METRICS_EXPORTER: otlp
    OTEL_LOGS_EXPORTER: otlp
services:
    demo:
        command: node --require @opentelemetry/auto-instrumentations-node/register app.js
```

* The usual `NODE_OPTIONS=--require …` doesn't work: Localdev [refuses `NODE_OPTIONS`](https://docs.localdev.build/configuration/environment-variables#variables-localdev-refuses). Put `--require` in the `command` instead.
* `--require` is resolved from the working directory, which is the Projectfile's directory. `node_modules` must be there.

## Other languages

Any OpenTelemetry SDK works if it exports OTLP to port 4998 (gRPC) or 4999 (HTTP). Only Go, Python and Node.js have been tested.

To use OTLP over HTTP, set both the protocol and the endpoint:

```yaml theme={null}
env:
    OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf
    OTEL_EXPORTER_OTLP_ENDPOINT: http://localhost:4999
```

If you changed the collector's ports with [`collector.receivers`](https://docs.localdev.build/configuration/introduction#collector), use those instead.

## Traces across services

A request that goes through several services shows as one trace only if each service passes the trace context on. In Go, wrap your HTTP clients and handlers with `otelhttp` (`go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp`). In Python and Node.js, auto-instrumentation does it for the libraries it supports.

## Incomplete and interrupted traces

* **INCOMPLETE** means the trace's root span hasn't arrived. Spans are sent when they end, so a long request or job shows as incomplete until it finishes. The list then shows the earliest span, marked **root missing**.
* **INTERRUPTED** means a service in the trace stopped (crashed or exited) before the trace finished. Spans it hadn't sent yet are lost. Check the service's **Output**.

## Services without instrumentation

A service that doesn't use OpenTelemetry still runs, and the UI still shows whether it's running, stopped or crashed. It sends no logs, metrics or traces. To see what it printed, open **Project → Services** and select **Output**, or read its output files (see [Files](https://docs.localdev.build/architecture.md#files)).

## If nothing arrives

* Wait 10 seconds. SDKs send spans and logs in batches, and metrics every 60 seconds unless you set `OTEL_METRIC_EXPORT_INTERVAL`.
* Check the service's stderr under **Output**. Some SDKs report export errors there; others fail without a word.
* If you set `OTEL_EXPORTER_OTLP_PROTOCOL` or `OTEL_EXPORTER_OTLP_ENDPOINT` yourself, check that they match: `grpc` with port 4998, or `http/protobuf` with port 4999.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.