Skip to content

Instantly share code, notes, and snippets.

@rain2307
Created August 24, 2023 00:03
Show Gist options
  • Save rain2307/82c0129196ed76f0f1b28d1a5534d1a4 to your computer and use it in GitHub Desktop.
Save rain2307/82c0129196ed76f0f1b28d1a5534d1a4 to your computer and use it in GitHub Desktop.
init tracing
use tracing_appender;
use tracing_error::ErrorLayer;
use tracing_subscriber::{self, fmt, prelude::*, registry::Registry};
pub fn init_tracing(directory: &str, file_name: &str) -> tracing_appender::non_blocking::WorkerGuard {
let file_appender = tracing_appender::rolling::hourly(directory, file_name);
let (non_blocking, guard) = tracing_appender::non_blocking(file_appender);
let file_log =
fmt::layer().with_ansi(false).with_thread_names(true).with_line_number(true).with_writer(non_blocking).pretty();
let console = fmt::layer().with_writer(std::io::stdout).with_line_number(true).pretty();
let error_layer = ErrorLayer::default();
Registry::default().with(console).with(file_log).with(error_layer).init();
guard
}
@rain2307
Copy link
Author

How do I set the logging level?

@rain2307
Copy link
Author

use tracing_appender;
use tracing_error::ErrorLayer;
use tracing_subscriber::{self, filter::LevelFilter, fmt, prelude::*, registry::Registry};

pub fn init_tracing(
    directory: &str, file_name: &str, level: LevelFilter,
) -> tracing_appender::non_blocking::WorkerGuard {
    let file_appender = tracing_appender::rolling::hourly(directory, file_name);
    let (non_blocking, guard) = tracing_appender::non_blocking(file_appender);

    let file_log = fmt::layer()
        .with_ansi(false)
        .with_thread_names(true)
        .with_line_number(true)
        .with_writer(non_blocking)
        .pretty()
        .with_filter(level);
    let console = fmt::layer().with_writer(std::io::stdout).with_line_number(true).pretty().with_filter(level);
    let error_layer = ErrorLayer::default().with_filter(level);
    Registry::default().with(console).with(file_log).with(error_layer).init();

    guard
}

@rain2307
Copy link
Author

It works now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment