Enable logging

This document describes how to enable logging in Rust. Logging requests and responses to the console can make it easier to troubleshoot applications.

Prerequisites

This guide uses the Secret Manager API, which must be enabled before you begin. To learn how to enable services, follow the service quickstart.

For complete setup instructions for the Rust libraries, see Getting started with Rust.

Dependencies

You must declare the dependencies in your Cargo.toml file:

cargo add google-cloud-secretmanager-v1 google-cloud-gax

Enable logging

The Rust client libraries use Tokio's tracing crate to collect scoped, structured, and async-aware diagnostics. The tracing crate separates sources of diagnostics (such as the Rust client libraries) from the components that collect these diagnostics using the Subscriber trait. There are many implementations available for the Subscriber. In this example we will use the fmt subscriber included with the tracing-subscriber crate.

  1. Add a dependency on the tracing-subscriber crate:

    cargo add tracing tracing-subscriber
    
  2. Write a function that receives the project ID as a function parameter:

    /// # Parameters
    /// - `project_id`: the id of a Google Cloud project, or its numeric ID.
    ///   For example: `my-project`.
    pub async fn sample(project_id: &str) -> anyhow::Result<()> {

  3. Introduce a few use declarations to make the example more readable:

    use google_cloud_gax::paginator::ItemPaginator;
    use google_cloud_secretmanager_v1::client::SecretManagerService;
    use tracing_subscriber;

  4. Initialize the default tracing subscriber:

    tracing_subscriber::fmt::init();

  5. Initialize a client with tracing enabled. Note the call to .with_tracing():

    let client = SecretManagerService::builder()
        .with_tracing()
        .build()
        .await?;

  6. Then use the client to send a request:

    let mut items = client
        .list_secrets()
        .set_parent(format!("projects/{project_id}"))
        .by_item();
    println!("listing all secrets in project {project_id}");
    while let Some(secret) = items.next().await.transpose()? {
        println!("  {secret:?}");
    }
    println!("DONE");

Expected output

The output (slightly edited for readability) will include a line such as:

2025-11-03T14:17:31.759452Z  INFO list_secrets{self=SecretManagerService ...

This line includes the request:

req=ListSecretsRequest { parent: "projects/... }

The response:

return=Ok(Response { parts: ..., body: ListSecretsResponse { ...

More information

The default subscriber created using tracing_subscriber::fmt::init() can be configured dynamically using the RUST_LOG environment variable. See its documentation for details.