This repository has been archived on 2026-03-27. You can view files and clone it, but you cannot make any changes to its state, such as pushing and creating new issues, pull requests or comments.
tracing/examples/examples/async-fn.rs
Hayden Stainsby bdbaf80073
examples: add note to examples that they are for tracing 0.2.0 (#3099)
It is not uncommon that users who are new to tracing look at the
examples in the `master` branch of the repository and find that they
don't compile. This is because they are examples which compile with the
code from the master branch, which is for the as yet unreleased tracing
0.2.0 ecosystem.

Users should instead go to the `v0.1.x` branch to find examples
compatible with the crates published on crates.io.

This change adds a doc-comment to the beginning of every example file
informing the user of this fact and suggesting that they check out the
`v0.1.x` branch instead.
2024-10-09 15:31:11 -04:00

60 lines
1.7 KiB
Rust

//! NOTE: This is pre-release documentation for the upcoming tracing 0.2.0 ecosystem. For the
//! release examples, please see the `v0.1.x` branch instead.
//!
//! Demonstrates using the `trace` attribute macro to instrument `async`
//! functions.
//!
//! This is based on the [`hello_world`] example from `tokio`. and implements a
//! simple client that opens a TCP stream, writes "hello world\n", and closes
//! the connection.
//!
//! You can test this out by running:
//!
//! nc -l 6142
//!
//! And then in another terminal run:
//!
//! cargo run --example async-fn
//!
//! [`hello_world`]: https://github.com/tokio-rs/tokio/blob/132e9f1da5965530b63554d7a1c59824c3de4e30/tokio/examples/hello_world.rs
#![deny(rust_2018_idioms)]
use tokio::io::AsyncWriteExt;
use tokio::net::TcpStream;
use tracing::info;
use tracing_attributes::instrument;
use std::{error::Error, io, net::SocketAddr};
#[instrument]
async fn connect(addr: &SocketAddr) -> io::Result<TcpStream> {
let stream = TcpStream::connect(&addr).await;
tracing::info!("created stream");
stream
}
#[instrument]
async fn write(stream: &mut TcpStream) -> io::Result<usize> {
let result = stream.write(b"hello world\n").await;
info!("wrote to stream; success={:?}", result.is_ok());
result
}
#[tokio::main]
pub async fn main() -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
let addr = "127.0.0.1:6142".parse()?;
tracing_subscriber::fmt()
.with_env_filter("async_fn=trace")
.try_init()?;
// Open a TCP stream to the socket address.
//
// Note that this is the Tokio TcpStream, which is fully async.
let mut stream = connect(&addr).await?;
write(&mut stream).await?;
Ok(())
}