tracing-better-stack 0.1.0

A tracing-subscriber layer for Better Stack (Logtail) logging
Documentation
use std::env;
use tracing::{Level, debug, error, info, span, warn};
use tracing_better_stack::{BetterStackConfig, BetterStackLayer};
use tracing_subscriber::prelude::*;

#[tokio::main]
async fn main() {
    // Get the Better Stack ingesting host from environment variable
    // (Better Stack provides hosts for each source, e.g., "s1234567.us-east-9.betterstackdata.com")
    let ingesting_host = env::var("BETTER_STACK_INGESTING_HOST")
        .expect("BETTER_STACK_INGESTING_HOST environment variable must be set");

    // Get the Better Stack source token from environment variable
    let source_token = env::var("BETTER_STACK_SOURCE_TOKEN")
        .expect("BETTER_STACK_SOURCE_TOKEN environment variable must be set");

    // Create the Better Stack layer with default configuration
    let better_stack_layer =
        BetterStackLayer::new(BetterStackConfig::builder(ingesting_host, source_token).build());

    // Create a tracing subscriber with the Better Stack layer
    // and a fmt layer for console output
    tracing_subscriber::registry()
        .with(better_stack_layer)
        .with(
            tracing_subscriber::fmt::layer()
                .with_target(false)
                .compact(),
        )
        .init();

    // Log some example messages
    info!("Application starting up");
    debug!("Debug information");
    warn!("This is a warning");

    // Example with structured fields
    info!(
        user_id = 123,
        action = "login",
        ip = "192.168.1.1",
        "User logged in successfully"
    );

    // Example with spans
    let span = span!(Level::INFO, "process_request", request_id = "abc123");
    let _enter = span.enter();

    info!("Processing request");

    // Simulate some work
    tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;

    info!("Request processed successfully");

    drop(_enter);

    // Example error
    error!(
        error_code = "DB_CONNECTION_FAILED",
        retry_count = 3,
        "Failed to connect to database"
    );

    // Give time for the logs to be sent
    tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;

    info!("Application shutting down");

    // Final sleep to ensure last batch is sent
    tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
}