Crate opentelemetry_derive

Crate opentelemetry_derive 

Source
Expand description

§Usage

Add the crate to your Cargo.toml:

opentelemetry_derive = "0.1"

You also need to have opentelemetry as a dependency, because the macros will generate code that references opentelemetry::{Key, KeyValue, StringValue, Value}. The version does not matter as long as it publishes those types.

§Key

If you do not set the key explicitly, the macro will autogenerate one, which will be your type’s name, lowercased:

use opentelemetry_derive::Key;

#[derive(Key)]
struct Auto;

#[derive(Key)]
#[otel(key = "custom")]
struct Overriden;

§Value

You must specify an intermediate type, into which your own type will be converted, that is itself already convertible into a Value:

use opentelemetry_derive::Value;

#[derive(Value)]
#[otel(variant = i64)]
struct Counter {
    count: i64,
}

impl From<&Counter> for i64 {
    fn from(value: &Counter) -> Self {
        value.count
    }
}

§StringValue

Your type must implement ToString (probably through Display):

use std::fmt;

use opentelemetry_derive::StringValue;

#[derive(StringValue)]
enum Method {
    Get,
    Post,
}

impl fmt::Display for Method {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}",
            match self {
                Self::Get => "get",
                Self::Post => "post",
            }
        )
    }
}

§KeyValue

References to your type must be both Into<Key> and Into<Value>:

use opentelemetry::{Key, Value};
use opentelemetry_derive::KeyValue;

#[derive(KeyValue)]
struct Config {
    value: bool,
}

const KEY: &str = "config";

impl From<&Config> for Key {
    fn from(_: &Config) -> Self {
        Self::from(KEY)
    }
}

impl From<&Config> for Value {
    fn from(value: &Config) -> Self {
        Value::from(value.value)
    }
}

Of course you can combine all the derives instead of manually implementing the required conversions:

use std::fmt;

use opentelemetry::StringValue;
use opentelemetry_derive::{Key, KeyValue, StringValue, Value};

#[derive(Key, KeyValue, StringValue, Value)]
#[otel(key = "req", variant = StringValue)]
struct Request {
    query: String,
}

impl fmt::Display for Request {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.query)
    }
}

Derive Macros§

Key
Derive conversion into Key.
KeyValue
Derive conversion into KeyValue.
StringValue
Derive conversion into StringValue.
Value
Derive conversion into Value.