Git Product home page Git Product logo

Comments (4)

krojew avatar krojew commented on July 29, 2024

I can make all the model structs public. Would that solve your use case?

from tracing-elastic-apm.

merc1031 avatar merc1031 commented on July 29, 2024

I think so. Let me try it locally with a cloned instance of the crate so you dont waste your time in case it doesnt work

from tracing-elastic-apm.

merc1031 avatar merc1031 commented on July 29, 2024

With the APMLayer made public, and the model structs (particularly Transaction), I was able to add a new layer that implements the logic I was looking for.

Essentially i had to Wrap APMLayer in a new layer that mostly just sent the function calls through to APMLayer, but modified Transaction.name in some cases.

I'm not sure if thats too much to ask for (or if its the right way to do this. I am somewhat new to Rust, new to tracing-subscriber, and to APM).

Code below


pub struct ApmAugmentLayer {
    inner_layer: ApmLayer,
}

impl ApmAugmentLayer {
    pub fn new(layer: ApmLayer) -> Self {
        ApmAugmentLayer { inner_layer: layer }
    }
}

struct MatchStrVisitor {
    field: String,
    value: Option<String>,
}

impl Visit for MatchStrVisitor {
    fn record_debug(&mut self, _field: &Field, _value: &dyn Debug) {}
    fn record_str(&mut self, field: &Field, value: &str) {
        if field.name() == self.field {
            self.value = Some(value.to_string());
        }
    }
}

struct NameOverrideValue(String);

impl<S> Layer<S> for ApmAugmentLayer
where
    S: Subscriber + for<'lookup> LookupSpan<'lookup>,
{
    fn on_new_span(&self, attrs: &Attributes<'_>, id: &Id, ctx: Context<'_, S>) {
        self.inner_layer.on_new_span(attrs, id, ctx);
    }

    fn on_record(&self, span: &Id, values: &Record<'_>, ctx: Context<'_, S>) {
        {
            let spanref = ctx.span(span).expect("Span not found!");
            let mut extensions = spanref.extensions_mut();
            let mut visitor = MatchStrVisitor {
                field: "name_override".to_string(),
                value: None,
            };
            values.record(&mut visitor);
            if let Some(name_override) = visitor.value {
                extensions.insert(NameOverrideValue(name_override.to_string()));
            };
        };
        self.inner_layer.on_record(span, values, ctx);
    }

    fn on_event(&self, event: &Event<'_>, ctx: Context<'_, S>) {
        self.inner_layer.on_event(event, ctx);
    }

    fn on_enter(&self, id: &Id, ctx: Context<'_, S>) {
        self.inner_layer.on_enter(id, ctx);
    }

    fn on_exit(&self, id: &Id, ctx: Context<'_, S>) {
        self.inner_layer.on_exit(id, ctx);
    }

    fn on_close(&self, id: Id, ctx: Context<'_, S>) {
        {
            let span = ctx.span(&id).expect("Span not found!");
            let mut extensions = span.extensions_mut();
            if let Some(name_override) = extensions.remove::<NameOverrideValue>() {
                if let Some(transaction) = extensions.get_mut::<Transaction>() {
                    transaction.name = Some(name_override.0)
                }
            }
        };
        self.inner_layer.on_close(id, ctx);
    }
}

Usage in middleware

pub async fn wrap_request(
    req: Request<axum::body::Body>,
    next: Next,
) -> Result<Response<axum::body::Body>, Infallible> {
    let request_id = req
        .headers()
        .get(X_PURE_REQUESTID)
        .and_then(|value| value.to_str().ok())
        .map(ToString::to_string);

    let response = match request_id {
        Some(request_id) => {
            let span = info_span!("request", %request_id, name_override = field::Empty);
            let _enter = span.enter();
            let (path, method) = {
                let path = if let Some(path) = req.extensions().get::<MatchedPath>() {
                    path.as_str()
                } else {
                    req.uri().path()
                };
                let method = req.method().clone();
                (path.to_owned(), method)
            };
            let res = next.run(req).in_current_span().await;
            let summ_status = match res.status().as_u16() {
                200..=299 => "2xx",
                300..=399 => "3xx",
                400..=499 => "4xx",
                500..=599 => "5xx",
                _ => "Unk",
            };

            span.record(
                "name_override",
                format!("HTTP {} {} {}", summ_status, method, path),
            );

            res
        }
        None => next.run(req).await,
    };

    Ok(response)
}

Tracing layers

    let apm_layer = tracing_elastic_apm::new_layer(
        service_name.to_owned(),
        tracing_elastic_apm::config::Config::new(url.clone()).with_authorization(
            tracing_elastic_apm::config::Authorization::ApiKey(
                tracing_elastic_apm::config::ApiKey::new(id, key),
            ),
        ),
    )
    .expect("Bad APM Config");

    tracing_subscriber::registry()
        .with(ApmAugmentLayer::new(apm_layer)

from tracing-elastic-apm.

merc1031 avatar merc1031 commented on July 29, 2024

Created this #20 , currently using it in production and it solved my issues

from tracing-elastic-apm.

Related Issues (9)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.