tracing: Adds init_for_tests (#10893)

This function is useful for tests. It will enable `TRACE` logging and also uses the libtest aware writer.
This commit is contained in:
Bastian Köcher
2022-02-21 13:08:24 +01:00
committed by GitHub
parent 8159c85b85
commit 7e8ff788b0
+20 -3
View File
@@ -108,6 +108,7 @@ pub use crate::types::{WASM_NAME_KEY, WASM_TARGET_KEY, WASM_TRACE_IDENTIFIER};
mod types; mod types;
/// Try to init a simple tracing subscriber with log compatibility layer. /// Try to init a simple tracing subscriber with log compatibility layer.
///
/// Ignores any error. Useful for testing. /// Ignores any error. Useful for testing.
#[cfg(feature = "std")] #[cfg(feature = "std")]
pub fn try_init_simple() { pub fn try_init_simple() {
@@ -117,6 +118,22 @@ pub fn try_init_simple() {
.try_init(); .try_init();
} }
/// Init a tracing subscriber for logging in tests.
///
/// Be aware that this enables `TRACE` by default. It also ignores any error
/// while setting up the logger.
///
/// The logs are not shown by default, logs are only shown when the test fails
/// or if [`nocapture`](https://doc.rust-lang.org/cargo/commands/cargo-test.html#display-options)
/// is being used.
#[cfg(feature = "std")]
pub fn init_for_tests() {
let _ = tracing_subscriber::fmt()
.with_max_level(tracing::Level::TRACE)
.with_test_writer()
.try_init();
}
/// Runs given code within a tracing span, measuring it's execution time. /// Runs given code within a tracing span, measuring it's execution time.
/// ///
/// If tracing is not enabled, the code is still executed. Pass in level and name or /// If tracing is not enabled, the code is still executed. Pass in level and name or
@@ -126,20 +143,20 @@ pub fn try_init_simple() {
/// ///
/// ``` /// ```
/// sp_tracing::within_span! { /// sp_tracing::within_span! {
/// sp_tracing::Level::TRACE, /// sp_tracing::Level::TRACE,
/// "test-span"; /// "test-span";
/// 1 + 1; /// 1 + 1;
/// // some other complex code /// // some other complex code
/// } /// }
/// ///
/// sp_tracing::within_span! { /// sp_tracing::within_span! {
/// sp_tracing::span!(sp_tracing::Level::WARN, "warn-span", you_can_pass="any params"); /// sp_tracing::span!(sp_tracing::Level::WARN, "warn-span", you_can_pass="any params");
/// 1 + 1; /// 1 + 1;
/// // some other complex code /// // some other complex code
/// } /// }
/// ///
/// sp_tracing::within_span! { /// sp_tracing::within_span! {
/// sp_tracing::debug_span!("debug-span", you_can_pass="any params"); /// sp_tracing::debug_span!("debug-span", you_can_pass="any params");
/// 1 + 1; /// 1 + 1;
/// // some other complex code /// // some other complex code
/// } /// }