Recording errors and exceptions with OpenTelemetry

Exceptions monitoring

Recording exceptions

To record errors and exceptions with OpenTelemetry, you need to:

  • Get the active span.
  • Call recordError function.
  • Optionally, set the span status code and message.

Go

import (
	"go.opentelemetry.io/otel/trace"
	"go.opentelemetry.io/otel/codes"
)

// Get the active span from the context.
span = trace.SpanFromContext(ctx)

if err != nil {
	// Record the error.
	span.RecordError(err)

	// Update the span status.
	span.SetStatus(codes.Error, err.Error())
}

See Go Tracing APIopen in new window for details.

Python

from opentelemetry import trace

span = trace.get_current_span()

except ValueError as exc:
    # Record the exception and update the span status.
    span.record_exception(exc)
    span.set_status(trace.Status(trace.StatusCode.ERROR, str(exc)))

See Python Tracing APIopen in new window for details.

Ruby

require 'opentelemetry'

span = OpenTelemetry::Trace.current_span

rescue Exception => e
  # Record the exception and update the span status.
  span.record_exception(e)
  span.status = OpenTelemetry::Trace::Status.error(e.to_s)
end

See Ruby Tracing APIopen in new window for details.

Java

import io.opentelemetry.api;

Span span = Span.current()

} catch (Throwable throwable) {
  span.setStatus(StatusCode.ERROR, "Something bad happened!");
  span.recordException(throwable);
}

See Java Tracing APIopen in new window for details.

.NET

var activity = Activity.Current;

catch (Exception ex)
{
    activity?.RecordException(ex);
    activity?.SetStatus(Status.Error.WithDescription(ex.Message));
}

See .NET Tracing APIopen in new window for details.

JavaScript

const otel = require('@opentelemetry/api')

const span = otel.trace.getSpan(otel.context.active())

} catch (exc) {
  // Record the exception and update the span status.
  span.recordException(exc)
  span.setStatus({ code: otel.SpanStatusCode.ERROR, message: String(exc) })
}

See JavaScript Tracing APIopen in new window for details.

PHP

use OpenTelemetry\API\Trace\Span;

$span = Span::getCurrent();

} catch (\Exception $exc) {
    $span->setStatus("error", $exc->getMessage());
    $span->recordException($exc);
}

See PHP Tracing APIopen in new window for details.

Grouping exceptions together

You can control how Uptrace groups exception together by providing grouping.fingerprint attribute which can be a string or a number (hash/id):

exception.type = "RuntimeError"
exception.message = "operation failed: 123 456 789"
grouping.fingerprint = "operation failed"

How to view exceptions?

Exceptions are displayed together with ERROR logs. To view exceptions:

  • In Uptrace UI, go to the "Traces & Logs" tab.

  • Click on the "Logs" button.

  • Optionally, select the "log:error" system.

Exceptions UI

Last Updated: