### Quick Start with Default Subscriber Source: https://docs.rs/tauri-plugin-tracing/latest/src/tauri_plugin_tracing/lib.rs.html?search=std%3A%3Avec A simplified setup for basic applications where the plugin handles all tracing configuration using `Builder::with_default_subscriber()`. ```rust use tauri_plugin_tracing::{Builder, LevelFilter}; tauri::Builder::default() .plugin( Builder::new() .with_max_level(LevelFilter::DEBUG) .with_default_subscriber() // Let plugin set up tracing .build(), ); // .run(tauri::generate_context!("examples/default-subscriber/src-tauri/tauri.conf.json")) ``` -------------------------------- ### Default Tracing Subscriber Setup Source: https://docs.rs/tauri-plugin-tracing/latest/index.html For simple applications, use `Builder::with_default_subscriber()` to let the plugin automatically handle the tracing setup. This is a quick way to enable tracing without manual configuration. ```rust tauri::Builder::default() .plugin( Builder::new() .with_max_level(LevelFilter::DEBUG) .with_default_subscriber() // Let plugin set up tracing .build(), ); // .run(tauri::generate_context!("examples/default-subscriber/src-tauri/tauri.conf.json")) ``` -------------------------------- ### Example Log Searches Source: https://docs.rs/tauri-plugin-tracing/latest/tauri_plugin_tracing/fn.log.html?search= Illustrative examples of search queries that can be performed within the logging system. ```text std::vec ``` ```text u32 -> bool ``` ```text Option, (T -> U) -> Option ``` -------------------------------- ### Setup Logging with Tauri Plugin Tracing Source: https://docs.rs/tauri-plugin-tracing/latest/src/tauri_plugin_tracing/lib.rs.html?search=u32+-%3E+bool Sets up the tracing plugin, including configuring logging levels, filters, and optional features like colored output and flamegraphs. This function is called during Tauri application setup. ```rust #[cfg(desktop)] if set_default_subscriber { let guard = acquire_logger( app, log_level, filter, custom_filter, custom_layer, &targets, rotation, rotation_strategy, max_file_size, timezone_strategy, format_options, #[cfg(feature = "colored")] use_colors, #[cfg(feature = "flamegraph")] enable_flamegraph, )?; // Store the guard in Tauri's state management to ensure logs flush on shutdown if guard.is_some() { app.manage(LogGuard(guard)); } } ``` -------------------------------- ### Setup Default Subscriber with File Logging Source: https://docs.rs/tauri-plugin-tracing/latest/src/tauri_plugin_tracing/lib.rs.html?search= Configures the default logging subscriber, including file logging with rotation and size limits. This setup is conditional on the 'desktop' feature. ```rust let guard = acquire_logger( app, log_level, filter, custom_filter, custom_layer, &targets, rotation, rotation_strategy, max_file_size, timezone_strategy, format_options, #[cfg(feature = "colored")] use_colors, #[cfg(feature = "flamegraph")] enable_flamegraph, )?; // Store the guard in Tauri's state management to ensure logs flush on shutdown if guard.is_some() { app.manage(LogGuard(guard)); } ``` -------------------------------- ### Tauri Plugin Setup with Logging Configuration Source: https://docs.rs/tauri-plugin-tracing/latest/src/tauri_plugin_tracing/lib.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Sets up the tracing plugin within a Tauri application, configuring various logging options such as log level, file targets, and colorization. This function is called during Tauri's setup phase. ```rust Self::plugin_builder() .setup(move |app, _api| { #[cfg(feature = "flamegraph")] setup_flamegraph(app); #[cfg(desktop)] if set_default_subscriber { let guard = acquire_logger( app, log_level, filter, custom_filter, custom_layer, &targets, rotation, rotation_strategy, max_file_size, timezone_strategy, format_options, #[cfg(feature = "colored")] use_colors, #[cfg(feature = "flamegraph")] enable_flamegraph, )?; // Store the guard in Tauri's state management to ensure logs flush on shutdown if guard.is_some() { app.manage(LogGuard(guard)); } } Ok(()) }) .build() ``` -------------------------------- ### Opt-in to Global Subscriber Setup Source: https://docs.rs/tauri-plugin-tracing/latest/src/tauri_plugin_tracing/lib.rs.html?search=std%3A%3Avec Call `with_default_subscriber()` to let the plugin handle all tracing setup, including registering the global subscriber. This is useful when you want the plugin to manage the entire tracing configuration based on the builder's settings. ```rust use tauri_plugin_tracing::{Builder, LevelFilter}; // Let the plugin set up everything tauri::Builder::default() .plugin( Builder::new() .with_max_level(LevelFilter::DEBUG) .with_file_logging() .with_default_subscriber() // Opt-in to global subscriber .build() ); // .run(tauri::generate_context!("examples/default-subscriber/src-tauri/tauri.conf.json")) ``` -------------------------------- ### Setup Logger with File and Console Output Source: https://docs.rs/tauri-plugin-tracing/latest/src/tauri_plugin_tracing/lib.rs.html?search=std%3A%3Avec Configures a logger to output debug messages to both the console with ANSI colors and a daily rolling file. This setup is useful for pre-Tauri initialization or when full control over subscriber configuration is needed. ```rust use tracing_subscriber::filter::Targets; use tracing_subscriber::layer::SubscriberExt; use tracing_subscriber::util::SubscriberInitExt; use tracing_subscriber::{fmt, registry}; use std::env; use std::fs; fn setup_logger() -> Builder { let log_dir = env::temp_dir().join("my-app"); let _ = fs::create_dir_all(&log_dir); let file_appender = tracing_appender::rolling::daily(&log_dir, "app"); let (non_blocking, guard) = tracing_appender::non_blocking(file_appender); std::mem::forget(guard); // Keep file logging active for app lifetime let targets = Targets::new() .with_default(Level::DEBUG) .with_target("hyper", Level::WARN) .with_target("reqwest", Level::WARN); registry() .with(fmt::layer().with_ansi(true)) .with(fmt::layer().with_writer(StripAnsiWriter::new(non_blocking)).with_ansi(false)) .with(targets) .init(); // Return minimal builder - logging is already configured Builder::new() } fn main() { let builder = setup_logger(); tauri::Builder::default() .plugin(builder.build()); // .run(tauri::generate_context!("examples/default-subscriber/src-tauri/tauri.conf.json")) } ``` -------------------------------- ### Rust parse() Method Examples Source: https://docs.rs/tauri-plugin-tracing/latest/tauri_plugin_tracing/struct.CallStackLine.html Shows how to use the `parse` method to convert a string slice into another type that implements the `FromStr` trait. Includes examples of basic usage, using the turbofish syntax for type inference, and handling parse errors. ```rust let four: u32 = "4".parse().unwrap(); assert_eq!(4, four); ``` ```rust let four = "4".parse::(); assert_eq!(Ok(4), four); ``` ```rust let nope = "j".parse::(); assert!(nope.is_err()); ``` -------------------------------- ### Rust String get Method Example Source: https://docs.rs/tauri-plugin-tracing/latest/tauri_plugin_tracing/struct.CallStackLine.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates safely retrieving a subslice of a string using the `get` method, which returns `None` for invalid or out-of-bounds indices. ```Rust let v = String::from("🗻∈🌏"); assert_eq!(Some("🗻"), v.get(0..4)); // indices not on UTF-8 sequence boundaries assert!(v.get(1..).is_none()); assert!(v.get(..8).is_none()); // out of bounds assert!(v.get(..42).is_none()); ``` -------------------------------- ### File Logging Setup Source: https://docs.rs/tauri-plugin-tracing/latest/index.html Configure the plugin for simple file logging using `Builder::with_file_logging()`. This enables basic file persistence for logs. ```rust Builder::new() .with_max_level(LevelFilter::DEBUG) .with_file_logging() .with_default_subscriber() .build::(); ``` -------------------------------- ### WebviewLayer Integration Example Source: https://docs.rs/tauri-plugin-tracing/latest/src/tauri_plugin_tracing/layer.rs.html?search= Demonstrates how to set up a custom tracing subscriber using the WebviewLayer to forward logs to the frontend. This is typically used when composing your own subscriber. ```rust use tauri_plugin_tracing::{Builder, WebviewLayer, LevelFilter}; use tracing_subscriber::{Registry, layer::SubscriberExt, util::SubscriberInitExt, fmt}; let builder = Builder::new() .with_max_level(LevelFilter::DEBUG); let filter = builder.build_filter(); tauri::Builder::default() .plugin(builder.build()) .setup(move |app| { Registry::default() .with(fmt::layer()) .with(WebviewLayer::new(app.handle().clone())) .with(filter) .init(); Ok(()) }); ``` -------------------------------- ### Rust String get_mut Method Modification Example Source: https://docs.rs/tauri-plugin-tracing/latest/tauri_plugin_tracing/struct.CallStackLine.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Shows how to safely get a mutable subslice, modify it (e.g., convert to uppercase), and observe the changes in the original string. ```Rust let mut v = String::from("hello"); assert_eq!("hello", v); { let s = v.get_mut(0..2); let s = s.map(|s| { s.make_ascii_uppercase(); &*s }); assert_eq!(Some("HE"), s); } assert_eq!("HEllo", v); ``` -------------------------------- ### Getting Slice Reference Source: https://docs.rs/tauri-plugin-tracing/latest/tauri_plugin_tracing/struct.LogMessage.html Provides an example of using `as_slice` to obtain a reference to the underlying slice. This is particularly useful for dereferencing container types like `Box<[T]>` or `Arc<[T]>` into a slice. ```rust let slice: &[i32] = &[1, 2, 3]; let slice_ref = slice.as_slice(); assert_eq!(slice, slice_ref); ``` -------------------------------- ### Configure Logging to Stdout and Webview Source: https://docs.rs/tauri-plugin-tracing/latest/tauri_plugin_tracing/enum.Target.html Example of setting up the logger to output logs to both stdout and the webview. This is the default behavior. ```rust use tauri_plugin_tracing::{Builder, Target}; // Log to stdout and webview (default behavior) Builder::new() .targets([Target::Stdout, Target::Webview]) .build::(); ``` -------------------------------- ### Rust String Split Examples Source: https://docs.rs/tauri-plugin-tracing/latest/tauri_plugin_tracing/struct.CallStackLine.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates various ways to split a string using the `split` method with different patterns like characters, strings, and closures. ```rust let v: Vec<&str> = "Mary had a little lamb".split(' ').collect(); assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]); ``` ```rust let v: Vec<&str> = "".split('X').collect(); assert_eq!(v, [""]); ``` ```rust let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect(); assert_eq!(v, ["lion", "", "tiger", "leopard"]); ``` ```rust let v: Vec<&str> = "lion::tiger::leopard".split("::").collect(); assert_eq!(v, ["lion", "tiger", "leopard"]); ``` ```rust let v: Vec<&str> = "AABBCC".split("DD").collect(); assert_eq!(v, ["AABBCC"]); ``` ```rust let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect(); assert_eq!(v, ["abc", "def", "ghi"]); ``` ```rust let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect(); assert_eq!(v, ["lion", "tiger", "leopard"]); ``` ```rust let v: Vec<&str> = "2020-11-03 23:59".split(&['-', ' ', ':', '@'][..]).collect(); assert_eq!(v, ["2020", "11", "03", "23", "59"]); ``` ```rust let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect(); assert_eq!(v, ["abc", "def", "ghi"]); ``` ```rust let x = "||||a||b|c".to_string(); let d: Vec<_> = x.split('|').collect(); assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]); ``` ```rust let x = "(///)".to_string(); let d: Vec<_> = x.split('/').collect(); assert_eq!(d, &["(", "", "", ")"]); ``` ```rust let d: Vec<_> = "010".split("0").collect(); assert_eq!(d, &["", "1", ""]); ``` ```rust let f: Vec<_> = "rust".split("").collect(); assert_eq!(f, &["", "r", "u", "s", "t", ""]); ``` ```rust let x = " a b c".to_string(); let d: Vec<_> = x.split(' ').collect(); assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]); ``` -------------------------------- ### Example Usage of StripAnsiWriter Source: https://docs.rs/tauri-plugin-tracing/latest/src/tauri_plugin_tracing/strip_ansi.rs.html Demonstrates how to integrate `StripAnsiWriter` with `tracing_subscriber` to ensure file logs are free of ANSI escape codes. This setup is useful when stdout layers use colors that should not be written to files. ```rust use tauri_plugin_tracing::StripAnsiWriter; use tauri_plugin_tracing::tracing_appender::non_blocking; use tauri_plugin_tracing::tracing_subscriber::{fmt, layer::SubscriberExt, util::SubscriberInitExt}; let file_appender = tracing_appender::rolling::daily("/tmp/logs", "app.log"); let (non_blocking, _guard) = non_blocking(file_appender); tracing_subscriber::registry() .with(fmt::layer()) // stdout with ANSI .with(fmt::layer().with_writer(StripAnsiWriter::new(non_blocking)).with_ansi(false)) .init(); ``` -------------------------------- ### Configure Log File Retention Source: https://docs.rs/tauri-plugin-tracing/latest/src/tauri_plugin_tracing/types.rs.html Use RotationStrategy enum variants to manage how many old log files are kept when the application starts. Examples show keeping all files, only one, or a specific number. ```rust use tauri_plugin_tracing::{Builder, RotationStrategy}; Builder::new() .with_file_logging() .with_rotation_strategy(RotationStrategy::KeepSome(7)) // Keep 7 most recent files .build::(); ``` -------------------------------- ### Example Usage of StripAnsiWriter with Tracing Subscriber Source: https://docs.rs/tauri-plugin-tracing/latest/tauri_plugin_tracing/struct.StripAnsiWriter.html?search= Demonstrates how to use StripAnsiWriter to configure tracing_subscriber. This setup sends formatted logs with ANSI codes to stdout while simultaneously writing a clean, non-ANSI version to a file using StripAnsiWriter. ```rust use tauri_plugin_tracing::StripAnsiWriter; use tauri_plugin_tracing::tracing_appender::non_blocking; use tauri_plugin_tracing::tracing_subscriber::{fmt, layer::SubscriberExt, util::SubscriberInitExt}; let file_appender = tracing_appender::rolling::daily("/tmp/logs", "app.log"); let (non_blocking, _guard) = non_blocking(file_appender); tracing_subscriber::registry() .with(fmt::layer()) // stdout with ANSI .with(fmt::layer().with_writer(StripAnsiWriter::new(non_blocking)).with_ansi(false)) .init(); ``` -------------------------------- ### Configure Logging to Stderr and Webview Source: https://docs.rs/tauri-plugin-tracing/latest/tauri_plugin_tracing/enum.Target.html Example demonstrating how to clear existing targets and set stderr as the console output destination, alongside the webview. ```rust use tauri_plugin_tracing::{Builder, Target}; // Log to stderr instead of stdout Builder::new() .clear_targets() .target(Target::Stderr) .target(Target::Webview) .build::(); ``` -------------------------------- ### Iterating Over Chunks from the End of a Slice Source: https://docs.rs/tauri-plugin-tracing/latest/tauri_plugin_tracing/struct.LogMessage.html Use `rchunks` to get an iterator over non-overlapping slices of a specified `chunk_size`, starting from the end of the original slice. The last chunk may be smaller if the slice length is not perfectly divisible by `chunk_size`. ```rust let slice = ['l', 'o', 'r', 'e', 'm']; let mut iter = slice.rchunks(2); assert_eq!(iter.next().unwrap(), &['e', 'm']); assert_eq!(iter.next().unwrap(), &['o', 'r']); assert_eq!(iter.next().unwrap(), &['l']); assert!(iter.next().is_none()); ``` -------------------------------- ### Early Initialization with Minimal Builder Source: https://docs.rs/tauri-plugin-tracing/latest/src/tauri_plugin_tracing/lib.rs.html?search=std%3A%3Avec Shows how to initialize tracing before creating the Tauri app for maximum control. This pattern uses `tracing_subscriber::registry()` with `init()` and passes a minimal `Builder` to the plugin. ```rust use tauri_plugin_tracing::{Builder, StripAnsiWriter, tracing_appender}; use tracing::Level; ``` -------------------------------- ### Creating a Box with System Allocator Source: https://docs.rs/tauri-plugin-tracing/latest/tauri_plugin_tracing/type.BoxedLayer.html?search= Demonstrates how to create a `Box` containing a value, using the `System` allocator. This API is experimental and requires the `allocator_api` feature. ```rust #![feature(allocator_api)] use std::alloc::System; let five = Box::new_in(5, System); ``` -------------------------------- ### Accessing Rust Vec data with raw pointers Source: https://docs.rs/tauri-plugin-tracing/latest/tauri_plugin_tracing/struct.LogMessage.html Demonstrates how to get a raw pointer to the vector's buffer using `as_ptr`. The example shows iterating through the vector's elements using pointer arithmetic. It also highlights the aliasing guarantees when mixing `as_ptr` and `as_mut_ptr`. ```rust let x = vec![1, 2, 4]; let x_ptr = x.as_ptr(); unsafe { for i in 0..x.len() { assert_eq!(*x_ptr.add(i), 1 << i); } } ``` ```rust unsafe { let mut v = vec![0, 1, 2]; let ptr1 = v.as_ptr(); let _ = ptr1.read(); let ptr2 = v.as_mut_ptr().offset(2); ptr2.write(2); // Notably, the write to `ptr2` did *not* invalidate `ptr1` // because it mutated a different element: let _ = ptr1.read(); } ``` -------------------------------- ### Get Implementation for Box Source: https://docs.rs/tauri-plugin-tracing/latest/tauri_plugin_tracing/type.BoxedLayer.html?search=std%3A%3Avec Provides the `get` method for `Box` when `T` also implements `Get<'a>`. ```APIDOC ### impl<'a, T> Get<'a> where T: Get<'a> #### fn get(i: &mut Iter<'a>) -> Option> Performs the get operation. ``` -------------------------------- ### Get Trait Implementation Source: https://docs.rs/tauri-plugin-tracing/latest/tauri_plugin_tracing/type.BoxedLayer.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Implementation of the Get trait for Box. ```APIDOC ### impl<'a, T> Get<'a> for Box where T: Get<'a>, #### fn get(i: &mut Iter<'a>) -> Option> Performs the get operation. Source§ ``` -------------------------------- ### Attempting to Create a Box with System Allocator Source: https://docs.rs/tauri-plugin-tracing/latest/tauri_plugin_tracing/type.BoxedLayer.html?search= Shows how to attempt creating a `Box` with the `System` allocator, returning a `Result` to handle potential allocation failures. This API is experimental and requires the `allocator_api` feature. ```rust #![feature(allocator_api)] use std::alloc::System; let five = Box::try_new_in(5, System)?; ``` -------------------------------- ### Unsafe Undefined Behavior Example Source: https://docs.rs/tauri-plugin-tracing/latest/tauri_plugin_tracing/type.Result.html?search= Shows an example of undefined behavior when `unwrap_unchecked` is called on an `Err` variant of `Result`. ```rust let x: Result = Err("emergency failure"); unsafe { x.unwrap_unchecked() }; // Undefined behavior! ``` -------------------------------- ### Getting Mutable String Slice from String Source: https://docs.rs/tauri-plugin-tracing/latest/tauri_plugin_tracing/struct.CallStackLine.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Illustrates how to get a mutable string slice (`&mut str`) from a `String` and modify it in place. ```rust let mut s = String::from("foobar"); let s_mut_str = s.as_mut_str(); s_mut_str.make_ascii_uppercase(); assert_eq!("FOOBAR", s_mut_str); ``` -------------------------------- ### Configure and Inspect Log Targets Source: https://docs.rs/tauri-plugin-tracing/latest/tauri_plugin_tracing/struct.Builder.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Sets up log targets and provides a way to inspect them. This is useful when integrating with custom subscriber setups to conditionally include specific logging layers. ```rust use tauri_plugin_tracing::{Builder, Target}; let builder = Builder::new() .target(Target::LogDir { file_name: None }); for target in builder.configured_targets() { match target { Target::Stdout => { /* add stdout layer */ }, Target::Stderr => { /* add stderr layer */ }, Target::Webview => { /* add WebviewLayer */ }, Target::LogDir { .. } | Target::Folder { .. } => { /* add file layer */ } } } ``` -------------------------------- ### Unsafe Undefined Behavior Example for Err Unwrapping Source: https://docs.rs/tauri-plugin-tracing/latest/tauri_plugin_tracing/type.Result.html?search= Shows an example of undefined behavior when `unwrap_err_unchecked` is called on an `Ok` variant of `Result`. ```rust let x: Result = Ok(2); unsafe { x.unwrap_err_unchecked() }; // Undefined behavior! ``` -------------------------------- ### Get Underlying Array Reference Source: https://docs.rs/tauri-plugin-tracing/latest/tauri_plugin_tracing/struct.LogMessage.html Attempts to get a reference to the underlying array if its size `N` matches the slice length. Returns `None` otherwise. ```rust let slice = &[1, 2, 3]; let arr_ref: Option<&[i32; 3]> = slice.as_array(); assert!(arr_ref.is_some()); let arr_ref_mismatch: Option<&[i32; 2]> = slice.as_array(); assert!(arr_ref_mismatch.is_none()); ``` -------------------------------- ### Get Mutable Underlying Array Reference Source: https://docs.rs/tauri-plugin-tracing/latest/tauri_plugin_tracing/struct.LogMessage.html Attempts to get a mutable reference to the underlying array if its size `N` matches the slice length. Returns `None` otherwise. ```rust let slice = &mut [1, 2, 3]; let arr_mut_ref: Option<&mut [i32; 3]> = slice.as_mut_array(); assert!(arr_mut_ref.is_some()); let arr_mut_ref_mismatch: Option<&mut [i32; 2]> = slice.as_mut_array(); assert!(arr_mut_ref_mismatch.is_none()); ``` -------------------------------- ### Basic String Splitting with `split` Source: https://docs.rs/tauri-plugin-tracing/latest/tauri_plugin_tracing/struct.CallStackLine.html?search= Demonstrates splitting a string by spaces, empty strings, specific characters, and character properties. ```rust let v: Vec<&str> = "Mary had a little lamb".split(' ').collect(); assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]); ``` ```rust let v: Vec<&str> = "".split('X').collect(); assert_eq!(v, [""]); ``` ```rust let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect(); assert_eq!(v, ["lion", "", "tiger", "leopard"]); ``` ```rust let v: Vec<&str> = "lion::tiger::leopard".split("::").collect(); assert_eq!(v, ["lion", "tiger", "leopard"]); ``` ```rust let v: Vec<&str> = "AABBCC".split("DD").collect(); assert_eq!(v, ["AABBCC"]); ``` ```rust let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect(); assert_eq!(v, ["abc", "def", "ghi"]); ``` ```rust let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect(); assert_eq!(v, ["lion", "tiger", "leopard"]); ``` -------------------------------- ### File Logging Setup Source: https://docs.rs/tauri-plugin-tracing/latest/src/tauri_plugin_tracing/lib.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Configures the plugin to log events to a file. This snippet shows how to enable file logging and use the default subscriber. ```rust # use tauri_plugin_tracing::{Builder, LevelFilter}; Builder::new() .with_max_level(LevelFilter::DEBUG) .with_file_logging() .with_default_subscriber() .build::(); ``` -------------------------------- ### Configure Log Output Targets Source: https://docs.rs/tauri-plugin-tracing/latest/src/tauri_plugin_tracing/lib.rs.html?search= Use this when setting up your own subscriber to determine which layers to include based on the configured targets. This example shows how to match configured targets to specific tracing subscriber layers. ```rust use tauri_plugin_tracing::{Builder, Target}; let builder = Builder::new() .target(Target::LogDir { file_name: None }); for target in builder.configured_targets() { match target { Target::Stdout => { /* add stdout layer */ } Target::Stderr => { /* add stderr layer */ } Target::Webview => { /* add WebviewLayer */ } Target::LogDir { .. } | Target::Folder { .. } => { /* add file layer */ } } } ``` -------------------------------- ### Getting references to Result values Source: https://docs.rs/tauri-plugin-tracing/latest/tauri_plugin_tracing/type.Result.html?search=std%3A%3Avec Use `as_ref()` to get a `Result<&T, &E>` from a `&Result`, allowing inspection without consuming the original Result. `as_mut()` provides mutable references. ```rust let x: Result = Ok(2); assert_eq!(x.as_ref(), Ok(&2)); let x: Result = Err("Error"); assert_eq!(x.as_ref(), Err(&"Error")); ``` ```rust fn mutate(r: &mut Result) { match r.as_mut() { Ok(v) => *v = 42, Err(e) => *e = 0, } } let mut x: Result = Ok(2); mutate(&mut x); assert_eq!(x.unwrap(), 42); let mut x: Result = Err(13); mutate(&mut x); assert_eq!(x.unwrap_err(), 0); ``` -------------------------------- ### Pinning a Box with System Allocator Source: https://docs.rs/tauri-plugin-tracing/latest/tauri_plugin_tracing/type.BoxedLayer.html?search= Demonstrates constructing a `Pin>` using the `System` allocator. This API is experimental and requires the `allocator_api` feature. ```rust #![feature(allocator_api)] use std::alloc::System; let x = Box::pin_in(1, System); ``` -------------------------------- ### Get Slice as Fixed-Size Array Reference Source: https://docs.rs/tauri-plugin-tracing/latest/tauri_plugin_tracing/struct.LogMessage.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Attempts to get a reference to the underlying data as a fixed-size array of length N. Returns None if N does not match the slice's length. ```rust let slice = &[1, 2, 3]; let arr_ref: Option<&[i32; 3]> = slice.as_array(); assert!(arr_ref.is_some()); let arr_ref_wrong_size: Option<&[i32; 2]> = slice.as_array(); assert!(arr_ref_wrong_size.is_none()); ``` -------------------------------- ### StripAnsiWriter Usage Example Source: https://docs.rs/tauri-plugin-tracing/latest/tauri_plugin_tracing/struct.StripAnsiWriter.html?search= An example demonstrating how to use StripAnsiWriter to configure tracing subscriber layers, ensuring that file output is free of ANSI escape codes while stdout might still include them. ```APIDOC ## Example Usage This example shows how to integrate `StripAnsiWriter` into a `tracing_subscriber` setup. It configures two layers: one for standard output (which may include ANSI codes) and another for file output (which uses `StripAnsiWriter` to remove ANSI codes). ```rust use tauri_plugin_tracing::StripAnsiWriter; use tauri_plugin_tracing::tracing_appender::non_blocking; use tauri_plugin_tracing::tracing_subscriber::{fmt, layer::SubscriberExt, util::SubscriberInitExt}; // Set up a rolling file appender for logs let file_appender = tracing_appender::rolling::daily("/tmp/logs", "app.log"); let (non_blocking, _guard) = non_blocking(file_appender); // Initialize the tracing subscriber tracing_subscriber::registry() // Add a layer for stdout, which will include ANSI color codes .with(fmt::layer()) // Add a layer for file output, using StripAnsiWriter to remove ANSI codes // and disabling ANSI for this layer explicitly. .with(fmt::layer().with_writer(StripAnsiWriter::new(non_blocking)).with_ansi(false)) .init(); ``` ``` -------------------------------- ### Binary Search By Key Example Source: https://docs.rs/tauri-plugin-tracing/latest/tauri_plugin_tracing/struct.LogMessage.html Shows how to use binary_search_by_key with a key extraction function to search in a slice of tuples, sorted by the second element. ```rust let s = [(0, 0), (2, 1), (4, 1), (5, 1), (3, 1), (1, 2), (2, 3), (4, 5), (5, 8), (3, 13), (1, 21), (2, 34), (4, 55)]; assert_eq!(s.binary_search_by_key(&13, |&(a, b)| b), Ok(9)); assert_eq!(s.binary_search_by_key(&4, |&(a, b)| b), Err(7)); assert_eq!(s.binary_search_by_key(&100, |&(a, b)| b), Err(13)); let r = s.binary_search_by_key(&1, |&(a, b)| b); assert!(match r { Ok(1..=4) => true, _ => false, }); ``` -------------------------------- ### Manually Creating a Box with System Allocator Source: https://docs.rs/tauri-plugin-tracing/latest/tauri_plugin_tracing/type.FilterFn.html?search= Illustrates manually creating a Box using the system allocator by allocating memory and then constructing the Box from a raw pointer. This is an experimental nightly API. ```rust #![feature(allocator_api, slice_ptr_get)] use std::alloc::{Allocator, System}; unsafe { let ptr = System.allocate(Layout::new::())?.as_mut_ptr() as *mut i32; // In general .write is required to avoid attempting to destruct // the (uninitialized) previous contents of `ptr`, though for this // simple example `*ptr = 5` would have worked as well. ptr.write(5); let x = Box::from_raw_in(ptr, System); } ``` -------------------------------- ### Basic Usage with Custom Subscriber Source: https://docs.rs/tauri-plugin-tracing/latest/src/tauri_plugin_tracing/lib.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to set up a custom tracing subscriber using WebviewLayer to forward logs to the frontend. This approach requires manual subscriber composition. ```rust # use tauri_plugin_tracing::{Builder, WebviewLayer, LevelFilter}; # use tracing_subscriber::{Registry, layer::SubscriberExt, util::SubscriberInitExt, fmt}; let tracing_builder = Builder::new() .with_max_level(LevelFilter::DEBUG) .with_target("hyper", LevelFilter::WARN); let filter = tracing_builder.build_filter(); tauri::Builder::default() .plugin(tracing_builder.build()) .setup(move |app| { Registry::default() .with(fmt::layer()) .with(WebviewLayer::new(app.handle().clone())) .with(filter) .init(); Ok(()) }); // .run(tauri::generate_context!("examples/default-subscriber/src-tauri/tauri.conf.json")) ``` -------------------------------- ### Creating a Zeroed Box with System Allocator Source: https://docs.rs/tauri-plugin-tracing/latest/tauri_plugin_tracing/type.BoxedLayer.html?search= Demonstrates creating a `Box` with memory initialized to zero bytes using the `System` allocator. `assume_init` is used to access the value. This API is experimental and requires the `allocator_api` feature. ```rust #![feature(allocator_api)] use std::alloc::System; let zero = Box::::new_zeroed_in(System); let zero = unsafe { zero.assume_init() }; assert_eq!(*zero, 0) ``` -------------------------------- ### Demonstration of a Poor `From>` Implementation Source: https://docs.rs/tauri-plugin-tracing/latest/tauri_plugin_tracing/type.BoxedLayer.html?search= Illustrates an example of an `impl From> for Pin` that introduces ambiguity when calling `Pin::from`. This is not recommended for crate implementations. ```rust struct Foo; impl From> for Pin { fn from(_: Box<()>) -> Pin { Pin::new(Foo) } } let foo = Box::new(()); let bar = Pin::from(foo); ``` -------------------------------- ### Basic Vec Initialization and Assertion Source: https://docs.rs/tauri-plugin-tracing/latest/tauri_plugin_tracing/struct.LogMessage.html Demonstrates basic vector creation and checking its length. ```rust let a = vec![1, 2, 3]; assert_eq!(a.len(), 3); ``` -------------------------------- ### try_get_i8 Source: https://docs.rs/tauri-plugin-tracing/latest/tauri_plugin_tracing/type.BoxedLayer.html?search=std%3A%3Avec Gets a signed 8-bit integer from `self`. ```APIDOC ## fn try_get_i8(&mut self) -> Result ### Description Gets a signed 8-bit integer from `self`. ### Method `try_get_i8` ### Parameters - `self`: A mutable reference to the type implementing this method. ### Returns - `Result`: Ok(i8) containing the signed 8-bit integer if successful, or an Err(TryGetError) if the operation failed. ``` -------------------------------- ### Constructor: WebviewLayer::new Source: https://docs.rs/tauri-plugin-tracing/latest/tauri_plugin_tracing/struct.WebviewLayer.html?search= Creates a new WebviewLayer instance. It requires an AppHandle to forward log events to the specified application. ```rust pub fn new(app_handle: AppHandle) -> Self ``` -------------------------------- ### try_get_u8 Source: https://docs.rs/tauri-plugin-tracing/latest/tauri_plugin_tracing/type.BoxedLayer.html?search=std%3A%3Avec Gets an unsigned 8-bit integer from `self`. ```APIDOC ## fn try_get_u8(&mut self) -> Result ### Description Gets an unsigned 8-bit integer from `self`. ### Method `try_get_u8` ### Parameters - `self`: A mutable reference to the type implementing this method. ### Returns - `Result`: Ok(u8) containing the unsigned 8-bit integer if successful, or an Err(TryGetError) if the operation failed. ``` -------------------------------- ### Basic String Splitting with split() Source: https://docs.rs/tauri-plugin-tracing/latest/tauri_plugin_tracing/struct.CallStackLine.html?search=u32+-%3E+bool Demonstrates splitting a string by various simple patterns like spaces, specific characters, and string slices. Shows how contiguous separators result in empty strings. ```rust let v: Vec<&str> = "Mary had a little lamb".split(' ').collect(); assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]); ``` ```rust let v: Vec<&str> = "".split('X').collect(); assert_eq!(v, [""]); ``` ```rust let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect(); assert_eq!(v, ["lion", "", "tiger", "leopard"]); ``` ```rust let v: Vec<&str> = "lion::tiger::leopard".split("::").collect(); assert_eq!(v, ["lion", "tiger", "leopard"]); ``` ```rust let v: Vec<&str> = "AABBCC".split("DD").collect(); assert_eq!(v, ["AABBCC"]); ``` -------------------------------- ### Binary Search Example Source: https://docs.rs/tauri-plugin-tracing/latest/tauri_plugin_tracing/struct.LogMessage.html Demonstrates binary search on a sorted slice, including cases where elements are found, not found, or have multiple occurrences. ```rust let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]; assert_eq!(s.binary_search(&13), Ok(9)); assert_eq!(s.binary_search(&4), Err(7)); assert_eq!(s.binary_search(&100), Err(13)); let r = s.binary_search(&1); assert!(match r { Ok(1..=4) => true, _ => false, }); ``` -------------------------------- ### Checking for String Prefix Source: https://docs.rs/tauri-plugin-tracing/latest/tauri_plugin_tracing/struct.CallStackLine.html Shows how to use `starts_with` to verify if a string slice begins with a given pattern. ```rust let bananas = "bananas"; assert!(bananas.starts_with("bana")); assert!(!bananas.starts_with("nana")); ``` -------------------------------- ### strip_prefix Source: https://docs.rs/tauri-plugin-tracing/latest/tauri_plugin_tracing/struct.LogMessage.html Returns a subslice with the prefix removed. If the slice starts with `prefix`, returns the subslice after the prefix, wrapped in `Some`. If `prefix` is empty, simply returns the original slice. If `prefix` is equal to the original slice, returns an empty slice. If the slice does not start with `prefix`, returns `None`. ```APIDOC ## pub fn strip_prefix

(&self, prefix: &P) -> Option<&[T]> where P: SlicePattern + ?Sized, T: PartialEq ### Description Returns a subslice with the prefix removed. If the slice starts with `prefix`, returns the subslice after the prefix, wrapped in `Some`. If `prefix` is empty, simply returns the original slice. If `prefix` is equal to the original slice, returns an empty slice. If the slice does not start with `prefix`, returns `None`. ### Parameters #### Path Parameters - **prefix** (&P) - Required - The prefix pattern to remove. ### Examples ```rust let v = &[10, 40, 30]; assert_eq!(v.strip_prefix(&[10]), Some(&[40, 30][..])); assert_eq!(v.strip_prefix(&[10, 40]), Some(&[30][..])); assert_eq!(v.strip_prefix(&[10, 40, 30]), Some(&[][..])); assert_eq!(v.strip_prefix(&[50]), None); assert_eq!(v.strip_prefix(&[10, 50]), None); let prefix : &str = "he"; assert_eq!(b"hello".strip_prefix(prefix.as_bytes()), Some(b"llo".as_ref())); ``` ``` -------------------------------- ### try_get_i8 Source: https://docs.rs/tauri-plugin-tracing/latest/tauri_plugin_tracing/type.FilterFn.html Attempts to get a signed 8-bit integer from the byte stream. ```APIDOC ## fn try_get_i8(&mut self) -> Result ### Description Gets a signed 8 bit integer from `self`. ### Method `try_get_i8` ### Parameters None ### Returns - `Result`: Ok(i8) if successful, or an error if the stream does not contain enough bytes. ``` -------------------------------- ### Creating an Uninitialized Box with System Allocator Source: https://docs.rs/tauri-plugin-tracing/latest/tauri_plugin_tracing/type.BoxedLayer.html?search= Demonstrates creating a `Box` with uninitialized contents using the `System` allocator. Initialization is deferred, and `assume_init` is used to access the value. This API is experimental and requires the `allocator_api` feature. ```rust #![feature(allocator_api)] use std::alloc::System; let mut five = Box::::new_uninit_in(System); // Deferred initialization: five.write(5); let five = unsafe { five.assume_init() }; assert_eq!(*five, 5) ``` -------------------------------- ### try_get_u8 Source: https://docs.rs/tauri-plugin-tracing/latest/tauri_plugin_tracing/type.FilterFn.html Attempts to get an unsigned 8-bit integer from the byte stream. ```APIDOC ## fn try_get_u8(&mut self) -> Result ### Description Gets an unsigned 8 bit integer from `self`. ### Method `try_get_u8` ### Parameters None ### Returns - `Result`: Ok(u8) if successful, or an error if the stream does not contain enough bytes. ``` -------------------------------- ### Using BoxedLayer with Builder Source: https://docs.rs/tauri-plugin-tracing/latest/tauri_plugin_tracing/type.BoxedLayer.html?search= Demonstrates how to create a custom tracing layer, box it using BoxedLayer, and add it to the tauri-plugin-tracing subscriber builder. ```rust use tauri_plugin_tracing::{Builder, BoxedLayer}; use tracing_subscriber::Layer; // Create a custom layer (e.g., from another crate) and box it let my_layer: BoxedLayer = tracing_subscriber::fmt::layer().boxed(); Builder::new() .with_layer(my_layer) .with_default_subscriber() .build::(); ``` -------------------------------- ### Rust binary_search Example Source: https://docs.rs/tauri-plugin-tracing/latest/tauri_plugin_tracing/struct.LogMessage.html Demonstrates binary searching a sorted slice for an element. Returns `Ok(index)` if found, or `Err(insertion_index)` if not found. ```rust let mut v = [1, 2, 3, 4, 5]; assert_eq!(v.binary_search(&3), Ok(2)); assert_eq!(v.binary_search(&6), Err(5)); ``` -------------------------------- ### iter Source: https://docs.rs/tauri-plugin-tracing/latest/tauri_plugin_tracing/struct.LogMessage.html Returns an iterator over the slice, yielding all items from start to end. ```APIDOC ## pub fn iter(&self) -> Iter<'_, T> ### Description Returns an iterator over the slice. The iterator yields all items from start to end. ### Examples ```rust let x = &[1, 2, 4]; let mut iterator = x.iter(); assert_eq!(iterator.next(), Some(&1)); assert_eq!(iterator.next(), Some(&2)); assert_eq!(iterator.next(), Some(&4)); assert_eq!(iterator.next(), None); ``` ``` -------------------------------- ### try_get_u32_ne Source: https://docs.rs/tauri-plugin-tracing/latest/tauri_plugin_tracing/type.BoxedLayer.html?search=std%3A%3Avec Gets an unsigned 32-bit integer from `self` in native-endian byte order. ```APIDOC ## fn try_get_u32_ne(&mut self) -> Result ### Description Gets an unsigned 32-bit integer from `self` in native-endian byte order. ### Method `try_get_u32_ne` ### Parameters - `self`: A mutable reference to the type implementing this method. ### Returns - `Result`: Ok(u32) containing the unsigned 32-bit integer in native-endian format, or an Err(TryGetError) if the operation failed. ``` -------------------------------- ### Demonstration of a Poor `From>` Impl Source: https://docs.rs/tauri-plugin-tracing/latest/tauri_plugin_tracing/type.BoxedLayer.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Illustrates a problematic implementation of `From>` for `Pin` that can lead to ambiguity. This is not recommended for crate implementations. ```rust struct Foo; // A type defined in this crate. impl From> for Pin { fn from(_: Box<()>) -> Pin { Pin::new(Foo) } } let foo = Box::new(()); let bar = Pin::from(foo); ``` -------------------------------- ### try_get_u32_le Source: https://docs.rs/tauri-plugin-tracing/latest/tauri_plugin_tracing/type.BoxedLayer.html?search=std%3A%3Avec Gets an unsigned 32-bit integer from `self` in little-endian byte order. ```APIDOC ## fn try_get_u32_le(&mut self) -> Result ### Description Gets an unsigned 32-bit integer from `self` in little-endian byte order. ### Method `try_get_u32_le` ### Parameters - `self`: A mutable reference to the type implementing this method. ### Returns - `Result`: Ok(u32) containing the unsigned 32-bit integer in little-endian format, or an Err(TryGetError) if the operation failed. ``` -------------------------------- ### Setting up WebviewLayer with a Custom Subscriber Source: https://docs.rs/tauri-plugin-tracing/latest/src/tauri_plugin_tracing/layer.rs.html?search=u32+-%3E+bool Demonstrates how to integrate the WebviewLayer into a custom tracing subscriber setup within a Tauri application. This is useful when you need to compose multiple layers, such as console output and webview forwarding, with specific filtering. ```rust use tauri_plugin_tracing::{Builder, WebviewLayer, LevelFilter}; use tracing_subscriber::{Registry, layer::SubscriberExt, util::SubscriberInitExt, fmt}; tauri::Builder::default() .plugin(builder.build()) .setup(move |app| { Registry::default() .with(fmt::layer()) .with(WebviewLayer::new(app.handle().clone())) .with(filter) .init(); Ok(()) }); ``` -------------------------------- ### Configure Webview Logging Layer Source: https://docs.rs/tauri-plugin-tracing/latest/src/tauri_plugin_tracing/lib.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Sets up a logging layer for webview output, conditionally enabled by `has_webview`. It requires an `app_handle` to interact with the webview. ```rust let webview_layer = if has_webview { Some(WebviewLayer::new(app_handle.clone())) } else { None }; ``` -------------------------------- ### try_get_u32 Source: https://docs.rs/tauri-plugin-tracing/latest/tauri_plugin_tracing/type.BoxedLayer.html?search=std%3A%3Avec Gets an unsigned 32-bit integer from `self` in big-endian byte order. ```APIDOC ## fn try_get_u32(&mut self) -> Result ### Description Gets an unsigned 32-bit integer from `self` in big-endian byte order. ### Method `try_get_u32` ### Parameters - `self`: A mutable reference to the type implementing this method. ### Returns - `Result`: Ok(u32) containing the unsigned 32-bit integer in big-endian format, or an Err(TryGetError) if the operation failed. ``` -------------------------------- ### try_get_i16_ne Source: https://docs.rs/tauri-plugin-tracing/latest/tauri_plugin_tracing/type.BoxedLayer.html?search=std%3A%3Avec Gets a signed 16-bit integer from `self` in native-endian byte order. ```APIDOC ## fn try_get_i16_ne(&mut self) -> Result ### Description Gets a signed 16-bit integer from `self` in native-endian byte order. ### Method `try_get_i16_ne` ### Parameters - `self`: A mutable reference to the type implementing this method. ### Returns - `Result`: Ok(i16) containing the signed 16-bit integer in native-endian format, or an Err(TryGetError) if the operation failed. ```