How to Prevent Infinite Logging Loop with Tokio-Tracing and Hyper in a Custom Subscriber in Rust?

Note – I have gone through Suppressing external library logs in a tokio tracing subscriber and How to turn off tracing events emitted by other crates?, and they don’t answer this question.

Context:

I’m creating a Tokio tracing subscriber that captures logs from tracing instrumented libraries and exports them to a backend service using the hyper crate. However, hyper is also instrumented with Tokio tracing, which causes an infinite logging loop because the logs generated by hyper are captured and exported by my subscriber.

Here’s a simplified version of my code:

use pin_project::pin_project;
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use tracing::info;
use tracing::Event;
use tracing::Metadata;
use tracing::Subscriber;
use tracing_core::span::Id;
use tracing_core::span::Record;

// Define a task-local variable for suppression
tokio::task_local! {
    static SUPPRESSED: bool;
}

struct SimpleSubscriber;

impl Subscriber for SimpleSubscriber {
    fn enabled(&self, _metadata: &Metadata<'_>) -> bool {
        !is_logging_suppressed()
    }

    fn new_span(&self, _: &tracing::span::Attributes<'_>) -> Id {
        Id::from_u64(10)
    }

    fn event(&self, event: &Event<'_>) {
        if is_logging_suppressed() {
            return;
        }

        // Extract the required metadata before moving into the async context
        let target = event.metadata().target().to_string();
        let name = event.metadata().name().to_string();
        let level = event.metadata().level().clone();

        let suppressed_future = SUPPRESSED.scope(true, async move {
            // the actual logging event, the hyper tracing event generated here should be suppressed
            hyper_wrapper::make_hyper_call("mock_upload_event", &target, &name, &level).await;
        });

        let suppress_logging_future = SuppressLogging {
            inner: suppressed_future,
        };

        // Use tokio::spawn instead of spawn_local
        tokio::task::spawn(suppress_logging_future);
    }

    fn record(&self, _: &Id, _: &Record<'_>) {}

    fn record_follows_from(&self, _: &Id, _: &Id) {}

    fn enter(&self, _: &Id) {}

    fn exit(&self, _: &Id) {}
}

#[pin_project]
struct SuppressLogging<F> {
    #[pin]
    inner: F,
}

impl<F: Future> Future for SuppressLogging<F> {
    type Output = F::Output;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let this = self.project();
        this.inner.poll(cx)
    }
}

fn is_logging_suppressed() -> bool {
    SUPPRESSED.try_with(|val| *val).unwrap_or(false)
}

#[tokio::main]
async fn main() {
    let subscriber = SimpleSubscriber;
    tracing::subscriber::set_global_default(subscriber)
        .expect("Setting default subscriber failed.");

    // Make a small Hyper call in the main method
    lib::some_func().await;
}

// Define the module within the same file
mod lib {
    use tracing::info;
    use tracing_core::Level;

    pub async fn some_func() {
        // this should be logged
        info!(name: "this-is-also-logged", "test");

        // the tracing event generated by hyper crate should not be suppressed.
        super::hyper_wrapper::make_hyper_call("main method", "main", "startup", &Level::INFO).await;
    }
}

mod hyper_wrapper {
    use hyper::Client;
    use hyper::Uri;
    use tracing_core::Level;

    pub async fn make_hyper_call(context: &str, target: &str, name: &str, level: &Level) {
        let client = Client::new();
        let uri = "http://www.google.com".parse::<Uri>().unwrap();
        let response = client.get(uri).await;
        match response {
            Ok(_response) => {
                //let _body = hyper::body::to_bytes(response).await.unwrap();
                println!(
                    "{} - [{}] - {} - {} ",
                    context,
                    level,
                    target,
                    name,
                );
            }
            Err(e) => {
                println!("{} - [{}] - {} - {} - Error: {:?}", context, level, target, name, e);
            }
        }
    }
}

Problem Statement:

  • I am creating a Tokio tracing subscriber, which gets the logs from the tokio-tracing instrumented libraries, and exports them to some backend service using (say) hyper.
  • Now the hyper crate is also instrumented with Tokio tracing, which results in the logs from this crate being received by the event() method of my subscriber and getting exported. This results in an infinite logging loop.
  • While I can try to create a filter to remove all the logs from the hyper crate, this crate could also be used by applications using my crate or the instrumented libraries used by this application. The application user/developer may not want the logs from the usage of hyper within their application to be filtered.
  • So, I want to filter only the logs generated by the hyper crate from within my subscriber implementation.
    I tried using tokio::task_local to set the suppression flag within my subscriber, and then use that to decide whether to export the logs or not. However, it seems that task_local won’t be propagated across multiple async calls made within the hyper crate.

Question:

What is the best way to achieve this? How can I filter out the logs generated by the hyper crate within my subscriber implementation without affecting the logs generated by the hyper crate in other parts of the application?

Please note that hyper is just one of those crates. My Subscriber would be using other crates like reqwest and tonic and it would be same issue with them.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật