---
source_url: https://www.pubnub.com/docs/sdks/rust/logging
title: Logging for Rust SDK
updated_at: 2026-05-22T11:07:49.971Z
sdk_name: PubNub Rust SDK
sdk_version: 0.7.0
---

> Documentation Index
> For a curated overview of PubNub documentation, see: https://www.pubnub.com/docs/llms.txt
> For the full list of all documentation pages, see: https://www.pubnub.com/docs/llms-full.txt


# Logging for Rust SDK

PubNub Rust SDK, use the latest version: 0.7.0

Install:

```bash
cargo add pubnub@0.7.0
```

This page explains how to enable logging in the PubNub Rust Software Development Kit (SDK) using standard Rust logging facilities.

## How to enable logging

The PubNub Rust SDK uses the standard Rust logging framework (`log` crate) internally. To capture these logs, you need to initialize a logger implementation in your application.

### Setup with env_logger

The simplest way to enable logging is to use the `env_logger` crate, which is included as a dependency of the SDK:

```rust
use std::env;
use std::error::Error;

use env_logger::{self, Env};
use log::{debug, error, info, warn};
use pubnub::{channel_groups::ChannelGroups, core::PubNubError, Keyset, PubNubClientBuilder};
use tokio;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    // Configure and initialize the logger before creating the PubNub client
    // You can control log level via the RUST_LOG environment variable
    // Examples:
    //   RUST_LOG=debug cargo run  # Show debug and higher logs
    //   RUST_LOG=info cargo run   # Show info and higher logs
    //   RUST_LOG=trace cargo run  # Show all logs
    env_logger::Builder::from_env(Env::default().default_filter_or("info"))
        .format_timestamp_millis()
        .init();

    info!("Initializing PubNub client with logging enabled");

    // Initialize PubNub client with demo keys
    let pubnub = PubNubClientBuilder::with_reqwest_transport()
        .with_keyset(Keyset {
            // Replace "demo" with your Publish Key from the PubNub Admin Portal
            publish_key: Some("demo"),
            // Replace "demo" with your Subscribe Key from the PubNub Admin Portal
            subscribe_key: "demo",
            secret_key: None,
        })
        .with_user_id("rust-logging-demo-user")
        .build()
        .map_err(|err| {
            error!("Failed to initialize PubNub client: {:?}", err);
            err
        })?;

    info!("PubNub client initialized successfully");
    debug!("Client configuration: subscribe_key=demo, user_id=rust-logging-demo-user");

    // Perform operations to generate logs
    perform_operations(&pubnub).await?;

    info!("Logging example completed");
    Ok(())
}

async fn perform_operations(
    pubnub: &pubnub::PubNubClient<reqwest::Client>,
) -> Result<(), PubNubError> {
    // Get PubNub time (simple operation to generate logs)
    info!("Fetching PubNub time to generate logs...");
    let time_result = pubnub.time().execute().await?;
    info!("Current PubNub time: {}", time_result);

    // Publish a message (generates more logs)
    let channel = "logging-demo-channel";
    info!("Publishing a message to channel '{}'...", channel);

    let publish_result = pubnub
        .publish_message("Hello from Rust logging example!")
        .channel(channel)
        .r#type("text-message")
        .execute()
        .await?;

    info!(
        "Message published with timetoken: {}",
        publish_result.timetoken
    );

    // Get Here Now data (generates more logs)
    info!("Fetching Here Now data...");
    let here_now_result = pubnub
        .here_now()
        .channels([channel.to_string()].to_vec())
        .include_state(true)
        .include_user_id(true)
        .execute()
        .await?;

    here_now_result.iter().for_each(|channel_data| {
        info!(
            "Channel: {}, Occupancy: {}",
            channel_data.name, channel_data.occupancy
        );
    });

    // Demonstrate different log levels
    debug!("This is a debug message - only shown when RUST_LOG includes debug level");
    info!("This is an info message - shown by default in this example");
    warn!("This is a warning message - shown by default and highlighted");
    error!("This is an error message - also shown by default and highlighted");

    Ok(())
}
```

## Log levels

The Rust SDK uses standard log levels from the `log` crate:

| Log Level | Description |
| --- | --- |
| `error` | Critical errors that may prevent the SDK from functioning correctly |
| `warn` | Warning conditions that don't prevent the SDK from functioning but might indicate issues |
| `info` | Informational messages about normal operations |
| `debug` | Detailed information useful for debugging |
| `trace` | Very detailed information about internal operations |

### Setting log levels

You can control which log messages are displayed by setting the `RUST_LOG` environment variable:

```bash
# Display all logs including debug information
RUST_LOG=debug cargo run

# Display only warnings and errors
RUST_LOG=warn cargo run

# Display all trace logs for the pubnub crate
RUST_LOG=pubnub=trace cargo run

# Display debug logs for pubnub and warning logs for everything else
RUST_LOG=warn,pubnub=debug cargo run
```

## Complete example

Here's a complete example showing how to set up logging with PubNub:

```rust
use std::error::Error;
use env_logger;
use log::{debug, error, info, warn};
use pubnub::{PubNubClientBuilder, Keyset};
use tokio;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    // Initialize the logger first - this should be done before any logging occurs
    env_logger::init();
    
    info!("Initializing PubNub client with logging enabled");
    
    // Then initialize PubNub with demo keys
    let client = PubNubClientBuilder::with_reqwest_transport()
        .with_keyset(Keyset {
            publish_key: Some("demo"), // Replace with your Publish Key from the PubNub Admin Portal
            subscribe_key: "demo",     // Replace with your Subscribe Key from the PubNub Admin Portal
            secret_key: None,
        })
        .with_user_id("logging-example-user")
        .build()
        .expect("Failed to create PubNub client");
    
    debug!("PubNub client initialized successfully");
    
    // Example operation to generate logs
    match client.time().execute().await {
        Ok(time) => {
            info!("Successfully retrieved PubNub time: {}", time);
        },
        Err(err) => {
            error!("Failed to retrieve time: {:?}", err);
        }
    }
    
    // Example publish operation
    let channel = "logging-demo-channel";
    match client.publish_message("Hello with logging!")
        .channel(channel)
        .execute()
        .await 
    {
        Ok(result) => {
            info!("Message published successfully to {} with timetoken: {}", 
                channel, result.timetoken);
        },
        Err(err) => {
            error!("Failed to publish message: {:?}", err);
        }
    }
    
    warn!("This is an example warning message");
    debug!("This is an example debug message - only visible with RUST_LOG=debug or lower");
    
    Ok(())
}
```