Crate myotel

Source
Expand description

§myotel

This is a foolproof best practice for initializing the integration of OpenTelemetry with the tracing library, providing support for logs, metrics, and trace.

§Features

  • Logs: Advanced logging capabilities integrated with OpenTelemetry.
  • Metrics: Flexible metric collection supporting various measurement types.
  • Trace: Rich distributed tracing tools for creating spans, adding events, and linking spans.

§Install

Run the following Cargo command in your project directory:

cargo add myotel

Or add the following line to your Cargo.toml:

myotel = "0.1"

§Examples

extern crate myotel;
use myotel::*;
use std::env;

#[tokio::main]
async fn main() {
    init_otel(default_config!()).await.unwrap();
    emit_log().await;
    println!("===========================================================");
    emit_span().await;
    println!("===========================================================");
    emit_metrics().await;
    shutdown_all_providers();
}

async fn emit_log() {
    info!("This is an info log message with OpenTelemetry integration");
    warn!("This is a warning log message with OpenTelemetry integration");
}

async fn emit_span() {
    let mut otel_span = tracer_span(SpanBuilder::from_name("example-span-1"), None);
    otel_span.set_attribute(KeyValue::new("attribute_key1", "attribute_value1"));
    otel_span.set_attribute(KeyValue::new("attribute_key2", "attribute_value2"));
    otel_span.add_event(
        "example-event-name-1",
        vec![KeyValue::new("event_attribute1", "event_value1")]
    );
    otel_span.add_link(
        SpanContext::new(
            TraceId::from_hex("58406520a006649127e371903a2de979").expect("invalid"),
            SpanId::from_hex("b6d7d7f6d7d6d7f6").expect("invalid"),
            TraceFlags::default(),
            false,
            TraceState::NONE
        ),
        vec![
            KeyValue::new("link_attribute1", "link_value1"),
            KeyValue::new("link_attribute2", "link_value2")
        ]
    );

    otel_span.add_link(
        SpanContext::new(
            TraceId::from_hex("23401120a001249127e371903f2de971").expect("invalid"),
            SpanId::from_hex("cd37d765d743d7f6").expect("invalid"),
            TraceFlags::default(),
            false,
            TraceState::NONE
        ),
        vec![
            KeyValue::new("link_attribute1", "link_value1"),
            KeyValue::new("link_attribute2", "link_value2")
        ]
    );
    (
        async {
            let _ = (
                {
                    info!("event-span-3");
                }
            ).instrument(info_span!("instrument span"));

            info!("event-name-20");
            let span2 = span!(Level::INFO, "example-span-2");
            let _enter = span2.enter();
            info!("event-name-2");
        }
    ).with_current_context_span(otel_span).await;
}

async fn emit_metrics() {
    env::set_var("OTEL_METRIC_EXPORT_INTERVAL", "1");
    env::set_var("OTEL_METRIC_EXPORT_TIMEOUT", "1");
    let meter = meter_provider().meter("stdout-example");
    // let meter = meter("stdout-example");
    let c = meter.u64_counter("example_counter").init();
    c.add(1, &[KeyValue::new("name", "apple"), KeyValue::new("color", "green")]);
    c.add(1, &[KeyValue::new("name", "apple"), KeyValue::new("color", "green")]);
    c.add(2, &[KeyValue::new("name", "apple"), KeyValue::new("color", "red")]);
    c.add(1, &[KeyValue::new("name", "banana"), KeyValue::new("color", "yellow")]);
    c.add(11, &[KeyValue::new("name", "banana"), KeyValue::new("color", "yellow")]);

    let h = meter.f64_histogram("example_histogram").init();
    h.record(1.0, &[KeyValue::new("name", "apple"), KeyValue::new("color", "green")]);
    h.record(1.0, &[KeyValue::new("name", "apple"), KeyValue::new("color", "green")]);
    h.record(2.0, &[KeyValue::new("name", "apple"), KeyValue::new("color", "red")]);
    h.record(1.0, &[KeyValue::new("name", "banana"), KeyValue::new("color", "yellow")]);
    h.record(11.0, &[KeyValue::new("name", "banana"), KeyValue::new("color", "yellow")]);
}

Re-exports§

pub use opentelemetry::metrics::MeterProvider as _;
pub use opentelemetry::trace::Span as _;
pub use opentelemetry::trace::TracerProvider as _;
pub use opentelemetry_semantic_conventions as semantic_conventions;
pub use tracing;

Modules§

event
Events represent single points in time during the execution of a program.
instrument
Attach a span to a std::future::Future.
otel_metrics
Re-export opentelemetry::metrics;
otel_trace
Re-export opentelemetry::trace;
span
Spans represent periods of time in which a program was executing in a particular context.

Macros§

debug
Constructs an event at the debug level.
debug_span
Constructs a span at the debug level.
default_config
Create the default InitConfig.
enabled
Checks whether a span or event is enabled based on the provided metadata.
error
Constructs an event at the error level.
error_span
Constructs a span at the error level.
event
Constructs a new Event.
event_enabled
Tests whether an event with the specified level and target would be enabled.
info
Constructs an event at the info level.
info_span
Constructs a span at the info level.
span
Constructs a new span.
span_enabled
Tests whether a span with the specified level and target would be enabled.
trace
Constructs an event at the trace level.
trace_span
Constructs a span at the trace level.
warn
Constructs an event at the warn level.
warn_span
Constructs a span at the warn level.

Structs§

ArcTracer
ArcTracer implement: Tracer + Sync + Send + ’static
BatchLogConfig
Batch log processor configuration. Use BatchConfigBuilder to configure your own instance of BatchConfig.
BatchTraceConfig
Batch span processor configuration. Use BatchConfigBuilder to configure your own instance of BatchConfig.
Context
An execution-scoped collection of values.
InitConfig
OpenTelemetry initialization configuration.
InstrumentationLibrary
Information about a library or crate providing instrumentation.
InstrumentationLibraryBuilder
Configuration options for InstrumentationLibrary.
Key
The key part of attribute KeyValue pairs.
KeyValue
A key-value pair describing an attribute.
Level
Describes the level of verbosity of a span or event.
Meter
Provides the ability to create instruments for recording measurements or accepting callbacks to report measurements.
MyIdGenerator
Generate trace_id using the Snowflake-inspired ULIDs (SULIDs), and generate span_id using a random number generator.
RandomIdGenerator
Default IdGenerator implementation.
SdkMeterProvider
Handles the creation and coordination of Meters.
SpanBuilder
SpanBuilder allows span attributes to be configured before the span has started.
SpanContext
Immutable portion of a Span which can be serialized and propagated.
SpanId
An 8-byte value which identifies a given span.
TraceFlags
Flags that can be set on a SpanContext.
TraceId
A 16-byte value which identifies a given trace.
TraceSpan
Single operation within a trace.
TraceState
TraceState carries system-specific configuration data, represented as a list of key-value pairs. TraceState allows multiple tracing systems to participate in the same trace.
Tracer
Tracer implementation to create and manage spans
TracerProviderConfig
Tracer configuration
WithContext
A future, stream, or sink that has an associated context.

Enums§

Array
A Value::Array containing homogeneous values.
Value
The value part of attribute KeyValue pairs.

Traits§

FutureExt
Extension trait allowing futures, streams, and sinks to be traced with a span.
FutureTraceExt
Extension trait allowing futures, streams, and sinks to be traced with a span.
IdGenerator
Interface for generating IDs
Instrument
Attaches spans to a std::future::Future.
OtelTracer
The interface for constructing Spans.
TraceContextExt
Methods for storing and retrieving trace data in a Context.

Functions§

arc_tracer
Returns the global Arc
get_active_span
Executes a closure with a reference to this thread’s current span.
get_text_map_propagator
Executes a closure with a reference to the current global TextMapPropagator propagator.
init_otel
Initialize OpenTelemetry.
logger_provider
Returns the global LoggerProvider
mark_span_as_active
Mark a given Span as active.
meter
Creates a named Meter via the configured GlobalMeterProvider.
meter_provider
Returns the global SdkMeterProvider
meter_with_version
Creates a Meter with the name, version and schema url.
set_text_map_propagator
Sets the given TextMapPropagator propagator as the current global propagator.
shutdown_all_providers
Shut down the current logger, tracer and meter providers.
tracer
Returns the global &’static Tracer
tracer_span
Create trace span customarily.

Attribute Macros§

instrument
Instruments a function to create and enter a tracing span every time the function is called.