mirror of
https://github.com/pezkuwichain/pezkuwi-subxt.git
synced 2026-06-12 17:01:09 +00:00
Run cargo fmt on the whole code base (#9394)
* Run cargo fmt on the whole code base * Second run * Add CI check * Fix compilation * More unnecessary braces * Handle weights * Use --all * Use correct attributes... * Fix UI tests * AHHHHHHHHH * 🤦 * Docs * Fix compilation * 🤷 * Please stop * 🤦 x 2 * More * make rustfmt.toml consistent with polkadot Co-authored-by: André Silva <andrerfosilva@gmail.com>
This commit is contained in:
@@ -16,23 +16,34 @@
|
||||
|
||||
//! Utilities for tracing block execution
|
||||
|
||||
use std::{collections::HashMap, sync::{Arc, atomic::{AtomicU64, Ordering}}, time::Instant};
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
sync::{
|
||||
atomic::{AtomicU64, Ordering},
|
||||
Arc,
|
||||
},
|
||||
time::Instant,
|
||||
};
|
||||
|
||||
use parking_lot::Mutex;
|
||||
use tracing::{Dispatch, dispatcher, Subscriber, Level, span::{Attributes, Record, Id}};
|
||||
use tracing::{
|
||||
dispatcher,
|
||||
span::{Attributes, Id, Record},
|
||||
Dispatch, Level, Subscriber,
|
||||
};
|
||||
|
||||
use crate::{SpanDatum, TraceEvent, Values};
|
||||
use sc_client_api::BlockBackend;
|
||||
use sc_rpc_server::RPC_MAX_PAYLOAD_DEFAULT;
|
||||
use sp_api::{Core, Metadata, ProvideRuntimeApi, Encode};
|
||||
use sp_api::{Core, Encode, Metadata, ProvideRuntimeApi};
|
||||
use sp_blockchain::HeaderBackend;
|
||||
use sp_core::hexdisplay::HexDisplay;
|
||||
use sp_rpc::tracing::{BlockTrace, Span, TraceBlockResponse, TraceError};
|
||||
use sp_runtime::{
|
||||
generic::BlockId,
|
||||
traits::{Block as BlockT, Header},
|
||||
};
|
||||
use sp_rpc::tracing::{BlockTrace, Span, TraceError, TraceBlockResponse};
|
||||
use sp_tracing::{WASM_NAME_KEY, WASM_TARGET_KEY, WASM_TRACE_IDENTIFIER};
|
||||
use sp_core::hexdisplay::HexDisplay;
|
||||
use crate::{SpanDatum, TraceEvent, Values};
|
||||
|
||||
// Heuristic for average event size in bytes.
|
||||
const AVG_EVENT: usize = 600 * 8;
|
||||
@@ -53,7 +64,7 @@ const BASE_PAYLOAD: usize = 100;
|
||||
const DEFAULT_TARGETS: &str = "pallet,frame,state";
|
||||
const TRACE_TARGET: &str = "block_trace";
|
||||
// The name of a field required for all events.
|
||||
const REQUIRED_EVENT_FIELD: &str = "method";
|
||||
const REQUIRED_EVENT_FIELD: &str = "method";
|
||||
const MEGABYTE: usize = 1024 * 1024;
|
||||
|
||||
/// Tracing Block Result type alias
|
||||
@@ -69,7 +80,7 @@ pub enum Error {
|
||||
#[error("Missing block component: {0}")]
|
||||
MissingBlockComponent(String),
|
||||
#[error("Dispatch error: {0}")]
|
||||
Dispatch(String)
|
||||
Dispatch(String),
|
||||
}
|
||||
|
||||
struct BlockSubscriber {
|
||||
@@ -82,10 +93,7 @@ struct BlockSubscriber {
|
||||
impl BlockSubscriber {
|
||||
fn new(targets: &str) -> Self {
|
||||
let next_id = AtomicU64::new(1);
|
||||
let mut targets: Vec<_> = targets
|
||||
.split(',')
|
||||
.map(crate::parse_target)
|
||||
.collect();
|
||||
let mut targets: Vec<_> = targets.split(',').map(crate::parse_target).collect();
|
||||
// Ensure that WASM traces are always enabled
|
||||
// Filtering happens when decoding the actual target / level
|
||||
targets.push((WASM_TRACE_IDENTIFIER.to_owned(), Level::TRACE));
|
||||
@@ -101,11 +109,11 @@ impl BlockSubscriber {
|
||||
impl Subscriber for BlockSubscriber {
|
||||
fn enabled(&self, metadata: &tracing::Metadata<'_>) -> bool {
|
||||
if !metadata.is_span() && !metadata.fields().field(REQUIRED_EVENT_FIELD).is_some() {
|
||||
return false;
|
||||
return false
|
||||
}
|
||||
for (target, level) in &self.targets {
|
||||
if metadata.level() <= level && metadata.target().starts_with(target) {
|
||||
return true;
|
||||
return true
|
||||
}
|
||||
}
|
||||
false
|
||||
@@ -125,7 +133,7 @@ impl Subscriber for BlockSubscriber {
|
||||
line: attrs.metadata().line().unwrap_or(0),
|
||||
start_time: Instant::now(),
|
||||
values,
|
||||
overall_time: Default::default()
|
||||
overall_time: Default::default(),
|
||||
};
|
||||
|
||||
self.spans.lock().insert(id.clone(), span);
|
||||
@@ -158,11 +166,9 @@ impl Subscriber for BlockSubscriber {
|
||||
self.events.lock().push(trace_event);
|
||||
}
|
||||
|
||||
fn enter(&self, _id: &Id) {
|
||||
}
|
||||
fn enter(&self, _id: &Id) {}
|
||||
|
||||
fn exit(&self, _span: &Id) {
|
||||
}
|
||||
fn exit(&self, _span: &Id) {}
|
||||
}
|
||||
|
||||
/// Holds a reference to the client in order to execute the given block.
|
||||
@@ -179,11 +185,15 @@ pub struct BlockExecutor<Block: BlockT, Client> {
|
||||
}
|
||||
|
||||
impl<Block, Client> BlockExecutor<Block, Client>
|
||||
where
|
||||
Block: BlockT + 'static,
|
||||
Client: HeaderBackend<Block> + BlockBackend<Block> + ProvideRuntimeApi<Block>
|
||||
+ Send + Sync + 'static,
|
||||
Client::Api: Metadata<Block>,
|
||||
where
|
||||
Block: BlockT + 'static,
|
||||
Client: HeaderBackend<Block>
|
||||
+ BlockBackend<Block>
|
||||
+ ProvideRuntimeApi<Block>
|
||||
+ Send
|
||||
+ Sync
|
||||
+ 'static,
|
||||
Client::Api: Metadata<Block>,
|
||||
{
|
||||
/// Create a new `BlockExecutor`
|
||||
pub fn new(
|
||||
@@ -193,7 +203,8 @@ impl<Block, Client> BlockExecutor<Block, Client>
|
||||
storage_keys: Option<String>,
|
||||
rpc_max_payload: Option<usize>,
|
||||
) -> Self {
|
||||
let rpc_max_payload = rpc_max_payload.map(|mb| mb.saturating_mul(MEGABYTE))
|
||||
let rpc_max_payload = rpc_max_payload
|
||||
.map(|mb| mb.saturating_mul(MEGABYTE))
|
||||
.unwrap_or(RPC_MAX_PAYLOAD_DEFAULT);
|
||||
Self { client, block, targets, storage_keys, rpc_max_payload }
|
||||
}
|
||||
@@ -205,10 +216,14 @@ impl<Block, Client> BlockExecutor<Block, Client>
|
||||
tracing::debug!(target: "state_tracing", "Tracing block: {}", self.block);
|
||||
// Prepare the block
|
||||
let id = BlockId::Hash(self.block);
|
||||
let mut header = self.client.header(id)
|
||||
let mut header = self
|
||||
.client
|
||||
.header(id)
|
||||
.map_err(|e| Error::InvalidBlockId(e))?
|
||||
.ok_or_else(|| Error::MissingBlockComponent("Header not found".to_string()))?;
|
||||
let extrinsics = self.client.block_body(&id)
|
||||
let extrinsics = self
|
||||
.client
|
||||
.block_body(&id)
|
||||
.map_err(|e| Error::InvalidBlockId(e))?
|
||||
.ok_or_else(|| Error::MissingBlockComponent("Extrinsics not found".to_string()))?;
|
||||
tracing::debug!(target: "state_tracing", "Found {} extrinsics", extrinsics.len());
|
||||
@@ -231,45 +246,46 @@ impl<Block, Client> BlockExecutor<Block, Client>
|
||||
);
|
||||
let _guard = dispatcher_span.enter();
|
||||
if let Err(e) = dispatcher::with_default(&dispatch, || {
|
||||
let span = tracing::info_span!(
|
||||
target: TRACE_TARGET,
|
||||
"trace_block",
|
||||
);
|
||||
let span = tracing::info_span!(target: TRACE_TARGET, "trace_block",);
|
||||
let _enter = span.enter();
|
||||
self.client.runtime_api().execute_block(&parent_id, block)
|
||||
}) {
|
||||
return Err(Error::Dispatch(format!("Failed to collect traces and execute block: {:?}", e).to_string()));
|
||||
return Err(Error::Dispatch(
|
||||
format!("Failed to collect traces and execute block: {:?}", e).to_string(),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
let block_subscriber = dispatch.downcast_ref::<BlockSubscriber>()
|
||||
.ok_or(Error::Dispatch(
|
||||
"Cannot downcast Dispatch to BlockSubscriber after tracing block".to_string()
|
||||
let block_subscriber =
|
||||
dispatch.downcast_ref::<BlockSubscriber>().ok_or(Error::Dispatch(
|
||||
"Cannot downcast Dispatch to BlockSubscriber after tracing block".to_string(),
|
||||
))?;
|
||||
let spans: Vec<_> = block_subscriber.spans
|
||||
let spans: Vec<_> = block_subscriber
|
||||
.spans
|
||||
.lock()
|
||||
.drain()
|
||||
// Patch wasm identifiers
|
||||
.filter_map(|(_, s)| patch_and_filter(SpanDatum::from(s), targets))
|
||||
.collect();
|
||||
let events: Vec<_> = block_subscriber.events
|
||||
let events: Vec<_> = block_subscriber
|
||||
.events
|
||||
.lock()
|
||||
.drain(..)
|
||||
.filter(|e| self.storage_keys
|
||||
.as_ref()
|
||||
.map(|keys| event_key_filter(e, keys))
|
||||
.unwrap_or(false)
|
||||
)
|
||||
.filter(|e| {
|
||||
self.storage_keys
|
||||
.as_ref()
|
||||
.map(|keys| event_key_filter(e, keys))
|
||||
.unwrap_or(false)
|
||||
})
|
||||
.map(|s| s.into())
|
||||
.collect();
|
||||
tracing::debug!(target: "state_tracing", "Captured {} spans and {} events", spans.len(), events.len());
|
||||
|
||||
let approx_payload_size = BASE_PAYLOAD + events.len() * AVG_EVENT + spans.len() * AVG_SPAN;
|
||||
let response = if approx_payload_size > self.rpc_max_payload {
|
||||
TraceBlockResponse::TraceError(TraceError {
|
||||
error:
|
||||
"Payload likely exceeds max payload size of RPC server.".to_string()
|
||||
})
|
||||
TraceBlockResponse::TraceError(TraceError {
|
||||
error: "Payload likely exceeds max payload size of RPC server.".to_string(),
|
||||
})
|
||||
} else {
|
||||
TraceBlockResponse::BlockTrace(BlockTrace {
|
||||
block_hash: block_id_as_string(id),
|
||||
@@ -286,14 +302,16 @@ impl<Block, Client> BlockExecutor<Block, Client>
|
||||
}
|
||||
|
||||
fn event_key_filter(event: &TraceEvent, storage_keys: &str) -> bool {
|
||||
event.values.string_values.get("key")
|
||||
event
|
||||
.values
|
||||
.string_values
|
||||
.get("key")
|
||||
.and_then(|key| Some(check_target(storage_keys, key, &event.level)))
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Filter out spans that do not match our targets and if the span is from WASM update its `name`
|
||||
/// and `target` fields to the WASM values for those fields.
|
||||
//
|
||||
// The `tracing` crate requires trace metadata to be static. This does not work for wasm code in
|
||||
// substrate, as it is regularly updated with new code from on-chain events. The workaround for this
|
||||
// is for substrate's WASM tracing wrappers to put the `name` and `target` data in the `values` map
|
||||
@@ -310,7 +328,7 @@ fn patch_and_filter(mut span: SpanDatum, targets: &str) -> Option<Span> {
|
||||
span.target = t;
|
||||
}
|
||||
if !check_target(targets, &span.target, &span.level) {
|
||||
return None;
|
||||
return None
|
||||
}
|
||||
}
|
||||
Some(span.into())
|
||||
@@ -320,15 +338,15 @@ fn patch_and_filter(mut span: SpanDatum, targets: &str) -> Option<Span> {
|
||||
fn check_target(targets: &str, target: &str, level: &Level) -> bool {
|
||||
for (t, l) in targets.split(',').map(crate::parse_target) {
|
||||
if target.starts_with(t.as_str()) && level <= &l {
|
||||
return true;
|
||||
return true
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn block_id_as_string<T: BlockT>(block_id: BlockId<T>) -> String {
|
||||
match block_id {
|
||||
match block_id {
|
||||
BlockId::Hash(h) => HexDisplay::from(&h.encode()).to_string(),
|
||||
BlockId::Number(n) => HexDisplay::from(&n.encode()).to_string()
|
||||
BlockId::Number(n) => HexDisplay::from(&n.encode()).to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,8 +34,10 @@ pub mod logging;
|
||||
use rustc_hash::FxHashMap;
|
||||
use serde::ser::{Serialize, SerializeMap, Serializer};
|
||||
use sp_tracing::{WASM_NAME_KEY, WASM_TARGET_KEY, WASM_TRACE_IDENTIFIER};
|
||||
use std::fmt;
|
||||
use std::time::{Duration, Instant};
|
||||
use std::{
|
||||
fmt,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use tracing::{
|
||||
event::Event,
|
||||
field::{Field, Visit},
|
||||
@@ -43,8 +45,10 @@ use tracing::{
|
||||
subscriber::Subscriber,
|
||||
Level,
|
||||
};
|
||||
use tracing_subscriber::layer::{Context, Layer};
|
||||
use tracing_subscriber::registry::LookupSpan;
|
||||
use tracing_subscriber::{
|
||||
layer::{Context, Layer},
|
||||
registry::LookupSpan,
|
||||
};
|
||||
|
||||
#[doc(hidden)]
|
||||
pub use tracing;
|
||||
@@ -137,10 +141,10 @@ impl Values {
|
||||
|
||||
/// Checks if all individual collections are empty
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.bool_values.is_empty()
|
||||
&& self.i64_values.is_empty()
|
||||
&& self.u64_values.is_empty()
|
||||
&& self.string_values.is_empty()
|
||||
self.bool_values.is_empty() &&
|
||||
self.i64_values.is_empty() &&
|
||||
self.u64_values.is_empty() &&
|
||||
self.string_values.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -162,15 +166,20 @@ impl Visit for Values {
|
||||
}
|
||||
|
||||
fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) {
|
||||
self.string_values.insert(field.name().to_string(), format!("{:?}", value).to_owned());
|
||||
self.string_values
|
||||
.insert(field.name().to_string(), format!("{:?}", value).to_owned());
|
||||
}
|
||||
}
|
||||
|
||||
impl Serialize for Values {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
let len = self.bool_values.len() + self.i64_values.len() + self.u64_values.len() + self.string_values.len();
|
||||
let len = self.bool_values.len() +
|
||||
self.i64_values.len() +
|
||||
self.u64_values.len() +
|
||||
self.string_values.len();
|
||||
let mut map = serializer.serialize_map(Some(len))?;
|
||||
for (k, v) in &self.bool_values {
|
||||
map.serialize_entry(k, v)?;
|
||||
@@ -194,7 +203,12 @@ impl fmt::Display for Values {
|
||||
let i64_iter = self.i64_values.iter().map(|(k, v)| format!("{}={}", k, v));
|
||||
let u64_iter = self.u64_values.iter().map(|(k, v)| format!("{}={}", k, v));
|
||||
let string_iter = self.string_values.iter().map(|(k, v)| format!("{}=\"{}\"", k, v));
|
||||
let values = bool_iter.chain(i64_iter).chain(u64_iter).chain(string_iter).collect::<Vec<String>>().join(", ");
|
||||
let values = bool_iter
|
||||
.chain(i64_iter)
|
||||
.chain(u64_iter)
|
||||
.chain(string_iter)
|
||||
.collect::<Vec<String>>()
|
||||
.join(", ");
|
||||
write!(f, "{}", values)
|
||||
}
|
||||
}
|
||||
@@ -217,16 +231,13 @@ impl ProfilingLayer {
|
||||
/// wasm_tracing indicates whether to enable wasm traces
|
||||
pub fn new_with_handler(trace_handler: Box<dyn TraceHandler>, targets: &str) -> Self {
|
||||
let targets: Vec<_> = targets.split(',').map(|s| parse_target(s)).collect();
|
||||
Self {
|
||||
targets,
|
||||
trace_handler,
|
||||
}
|
||||
Self { targets, trace_handler }
|
||||
}
|
||||
|
||||
fn check_target(&self, target: &str, level: &Level) -> bool {
|
||||
for t in &self.targets {
|
||||
if target.starts_with(t.0.as_str()) && level <= &t.1 {
|
||||
return true;
|
||||
return true
|
||||
}
|
||||
}
|
||||
false
|
||||
@@ -245,8 +256,8 @@ fn parse_target(s: &str) -> (String, Level) {
|
||||
} else {
|
||||
(target, Level::TRACE)
|
||||
}
|
||||
}
|
||||
None => (s.to_string(), Level::TRACE)
|
||||
},
|
||||
None => (s.to_string(), Level::TRACE),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -329,10 +340,7 @@ where
|
||||
if let Some(mut span_datum) = extensions.remove::<SpanDatum>() {
|
||||
span_datum.overall_time += end_time - span_datum.start_time;
|
||||
if span_datum.name == WASM_TRACE_IDENTIFIER {
|
||||
span_datum
|
||||
.values
|
||||
.bool_values
|
||||
.insert("wasm".to_owned(), true);
|
||||
span_datum.values.bool_values.insert("wasm".to_owned(), true);
|
||||
if let Some(n) = span_datum.values.string_values.remove(WASM_NAME_KEY) {
|
||||
span_datum.name = n;
|
||||
}
|
||||
@@ -404,13 +412,11 @@ impl TraceHandler for LogTraceHandler {
|
||||
|
||||
impl From<TraceEvent> for sp_rpc::tracing::Event {
|
||||
fn from(trace_event: TraceEvent) -> Self {
|
||||
let data = sp_rpc::tracing::Data {
|
||||
string_values: trace_event.values.string_values
|
||||
};
|
||||
let data = sp_rpc::tracing::Data { string_values: trace_event.values.string_values };
|
||||
sp_rpc::tracing::Event {
|
||||
target: trace_event.target,
|
||||
data,
|
||||
parent_id: trace_event.parent_id.map(|id| id.into_u64())
|
||||
parent_id: trace_event.parent_id.map(|id| id.into_u64()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -453,18 +459,12 @@ mod tests {
|
||||
fn setup_subscriber() -> (
|
||||
impl tracing::Subscriber + Send + Sync,
|
||||
Arc<Mutex<Vec<SpanDatum>>>,
|
||||
Arc<Mutex<Vec<TraceEvent>>>
|
||||
Arc<Mutex<Vec<TraceEvent>>>,
|
||||
) {
|
||||
let spans = Arc::new(Mutex::new(Vec::new()));
|
||||
let events = Arc::new(Mutex::new(Vec::new()));
|
||||
let handler = TestTraceHandler {
|
||||
spans: spans.clone(),
|
||||
events: events.clone(),
|
||||
};
|
||||
let layer = ProfilingLayer::new_with_handler(
|
||||
Box::new(handler),
|
||||
"test_target",
|
||||
);
|
||||
let handler = TestTraceHandler { spans: spans.clone(), events: events.clone() };
|
||||
let layer = ProfilingLayer::new_with_handler(Box::new(handler), "test_target");
|
||||
let subscriber = tracing_subscriber::fmt().with_writer(std::io::sink).finish().with(layer);
|
||||
(subscriber, spans, events)
|
||||
}
|
||||
@@ -542,7 +542,10 @@ mod tests {
|
||||
let _sub_guard = tracing::subscriber::set_default(sub);
|
||||
tracing::event!(target: "test_target", tracing::Level::INFO, "test_event");
|
||||
let mut te1 = events.lock().remove(0);
|
||||
assert_eq!(te1.values.string_values.remove(&"message".to_owned()).unwrap(), "test_event".to_owned());
|
||||
assert_eq!(
|
||||
te1.values.string_values.remove(&"message".to_owned()).unwrap(),
|
||||
"test_event".to_owned()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -557,7 +560,7 @@ mod tests {
|
||||
// emit event
|
||||
tracing::event!(target: "test_target", tracing::Level::INFO, "test_event");
|
||||
|
||||
//exit span
|
||||
// exit span
|
||||
drop(_guard1);
|
||||
drop(span1);
|
||||
|
||||
@@ -596,7 +599,7 @@ mod tests {
|
||||
tracing::event!(target: "test_target", tracing::Level::INFO, "test_event1");
|
||||
for msg in rx.recv() {
|
||||
if msg == false {
|
||||
break;
|
||||
break
|
||||
}
|
||||
}
|
||||
// guard2 and span2 dropped / exited
|
||||
|
||||
@@ -63,12 +63,7 @@ pub fn reload_filter() -> Result<(), String> {
|
||||
let mut env_filter = EnvFilter::default();
|
||||
if let Some(current_directives) = CURRENT_DIRECTIVES.get() {
|
||||
// Use join and then split in case any directives added together
|
||||
for directive in current_directives
|
||||
.lock()
|
||||
.join(",")
|
||||
.split(',')
|
||||
.map(|d| d.parse())
|
||||
{
|
||||
for directive in current_directives.lock().join(",").split(',').map(|d| d.parse()) {
|
||||
match directive {
|
||||
Ok(dir) => env_filter = env_filter.add_directive(dir),
|
||||
Err(invalid_directive) => {
|
||||
@@ -77,7 +72,7 @@ pub fn reload_filter() -> Result<(), String> {
|
||||
"Unable to parse directive while setting log filter: {:?}",
|
||||
invalid_directive,
|
||||
);
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -99,14 +94,9 @@ pub fn reload_filter() -> Result<(), String> {
|
||||
///
|
||||
/// Includes substrate defaults and CLI supplied directives.
|
||||
pub fn reset_log_filter() -> Result<(), String> {
|
||||
let directive = DEFAULT_DIRECTIVES
|
||||
.get_or_init(|| Mutex::new(Vec::new()))
|
||||
.lock()
|
||||
.clone();
|
||||
let directive = DEFAULT_DIRECTIVES.get_or_init(|| Mutex::new(Vec::new())).lock().clone();
|
||||
|
||||
*CURRENT_DIRECTIVES
|
||||
.get_or_init(|| Mutex::new(Vec::new()))
|
||||
.lock() = directive;
|
||||
*CURRENT_DIRECTIVES.get_or_init(|| Mutex::new(Vec::new())).lock() = directive;
|
||||
reload_filter()
|
||||
}
|
||||
|
||||
|
||||
@@ -79,11 +79,11 @@ where
|
||||
match current_thread.name() {
|
||||
Some(name) => {
|
||||
write!(writer, "{} ", FmtThreadName::new(name))?;
|
||||
}
|
||||
},
|
||||
// fall-back to thread id when name is absent and ids are not enabled
|
||||
None => {
|
||||
write!(writer, "{:0>2?} ", current_thread.id())?;
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -98,7 +98,7 @@ where
|
||||
let exts = span.extensions();
|
||||
if let Some(prefix) = exts.get::<super::layers::Prefix>() {
|
||||
write!(writer, "{}", prefix.as_str())?;
|
||||
break;
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -125,11 +125,11 @@ where
|
||||
writer: &mut dyn fmt::Write,
|
||||
event: &Event,
|
||||
) -> fmt::Result {
|
||||
if self.dup_to_stdout && (
|
||||
event.metadata().level() == &Level::INFO ||
|
||||
event.metadata().level() == &Level::WARN ||
|
||||
event.metadata().level() == &Level::ERROR
|
||||
) {
|
||||
if self.dup_to_stdout &&
|
||||
(event.metadata().level() == &Level::INFO ||
|
||||
event.metadata().level() == &Level::WARN ||
|
||||
event.metadata().level() == &Level::ERROR)
|
||||
{
|
||||
let mut out = String::new();
|
||||
self.format_event_custom(CustomFmtContext::FmtContext(ctx), &mut out, event)?;
|
||||
writer.write_str(&out)?;
|
||||
@@ -271,9 +271,8 @@ where
|
||||
) -> fmt::Result {
|
||||
match self {
|
||||
CustomFmtContext::FmtContext(fmt_ctx) => fmt_ctx.format_fields(writer, fields),
|
||||
CustomFmtContext::ContextWithFormatFields(_ctx, fmt_fields) => {
|
||||
fmt_fields.format_fields(writer, fields)
|
||||
}
|
||||
CustomFmtContext::ContextWithFormatFields(_ctx, fmt_fields) =>
|
||||
fmt_fields.format_fields(writer, fields),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -321,11 +320,7 @@ impl<'a> fmt::Write for MaybeColorWriter<'a> {
|
||||
impl<'a> MaybeColorWriter<'a> {
|
||||
/// Creates a new instance.
|
||||
fn new(enable_color: bool, inner_writer: &'a mut dyn fmt::Write) -> Self {
|
||||
Self {
|
||||
enable_color,
|
||||
inner_writer,
|
||||
buffer: String::new(),
|
||||
}
|
||||
Self { enable_color, inner_writer, buffer: String::new() }
|
||||
}
|
||||
|
||||
/// Write the buffered content to the `inner_writer`.
|
||||
|
||||
@@ -40,11 +40,7 @@ pub struct ConsoleLogLayer<S, N = tracing_subscriber::fmt::format::DefaultFields
|
||||
impl<S, T> ConsoleLogLayer<S, tracing_subscriber::fmt::format::DefaultFields, T> {
|
||||
/// Create a new [`ConsoleLogLayer`] using the `EventFormat` provided in argument.
|
||||
pub fn new(event_format: EventFormat<T>) -> Self {
|
||||
Self {
|
||||
event_format,
|
||||
fmt_fields: Default::default(),
|
||||
_inner: std::marker::PhantomData,
|
||||
}
|
||||
Self { event_format, fmt_fields: Default::default(), _inner: std::marker::PhantomData }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -90,11 +86,11 @@ where
|
||||
Ok(buf) => {
|
||||
a = buf;
|
||||
&mut *a
|
||||
}
|
||||
},
|
||||
_ => {
|
||||
b = String::new();
|
||||
&mut b
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
if self.format_event(&ctx, &mut buf, event).is_ok() {
|
||||
|
||||
@@ -42,12 +42,12 @@ where
|
||||
"newly created span with ID {:?} did not exist in the registry; this is a bug!",
|
||||
id
|
||||
);
|
||||
return;
|
||||
}
|
||||
return
|
||||
},
|
||||
};
|
||||
|
||||
if span.name() != PREFIX_LOG_SPAN {
|
||||
return;
|
||||
return
|
||||
}
|
||||
|
||||
let mut extensions = span.extensions_mut();
|
||||
|
||||
@@ -33,10 +33,9 @@ use std::io;
|
||||
use tracing::Subscriber;
|
||||
use tracing_subscriber::{
|
||||
filter::LevelFilter,
|
||||
fmt::time::ChronoLocal,
|
||||
fmt::{
|
||||
format, FormatEvent, FormatFields, Formatter, Layer as FmtLayer, MakeWriter,
|
||||
SubscriberBuilder,
|
||||
format, time::ChronoLocal, FormatEvent, FormatFields, Formatter, Layer as FmtLayer,
|
||||
MakeWriter, SubscriberBuilder,
|
||||
},
|
||||
layer::{self, SubscriberExt},
|
||||
registry::LookupSpan,
|
||||
@@ -153,9 +152,7 @@ where
|
||||
let max_level_hint = Layer::<FmtSubscriber>::max_level_hint(&env_filter);
|
||||
let max_level = to_log_level_filter(max_level_hint);
|
||||
|
||||
tracing_log::LogTracer::builder()
|
||||
.with_max_level(max_level)
|
||||
.init()?;
|
||||
tracing_log::LogTracer::builder().with_max_level(max_level).init()?;
|
||||
|
||||
// If we're only logging `INFO` entries then we'll use a simplified logging format.
|
||||
let simple = match max_level_hint {
|
||||
@@ -276,23 +273,19 @@ impl LoggerBuilder {
|
||||
}
|
||||
} else {
|
||||
if self.log_reloading {
|
||||
let subscriber = prepare_subscriber(
|
||||
&self.directives,
|
||||
None,
|
||||
self.force_colors,
|
||||
|builder| enable_log_reloading!(builder),
|
||||
)?;
|
||||
let subscriber =
|
||||
prepare_subscriber(&self.directives, None, self.force_colors, |builder| {
|
||||
enable_log_reloading!(builder)
|
||||
})?;
|
||||
|
||||
tracing::subscriber::set_global_default(subscriber)?;
|
||||
|
||||
Ok(())
|
||||
} else {
|
||||
let subscriber = prepare_subscriber(
|
||||
&self.directives,
|
||||
None,
|
||||
self.force_colors,
|
||||
|builder| builder,
|
||||
)?;
|
||||
let subscriber =
|
||||
prepare_subscriber(&self.directives, None, self.force_colors, |builder| {
|
||||
builder
|
||||
})?;
|
||||
|
||||
tracing::subscriber::set_global_default(subscriber)?;
|
||||
|
||||
@@ -410,12 +403,7 @@ mod tests {
|
||||
.unwrap();
|
||||
|
||||
let output = String::from_utf8(output.stderr).unwrap();
|
||||
assert!(
|
||||
re.is_match(output.trim()),
|
||||
"Expected:\n{}\nGot:\n{}",
|
||||
re,
|
||||
output,
|
||||
);
|
||||
assert!(re.is_match(output.trim()), "Expected:\n{}\nGot:\n{}", re, output,);
|
||||
}
|
||||
|
||||
/// This is not an actual test, it is used by the `prefix_in_log_lines` test.
|
||||
@@ -460,12 +448,7 @@ mod tests {
|
||||
.unwrap();
|
||||
|
||||
let output = String::from_utf8(output.stderr).unwrap();
|
||||
assert!(
|
||||
re.is_match(output.trim()),
|
||||
"Expected:\n{}\nGot:\n{}",
|
||||
re,
|
||||
output,
|
||||
);
|
||||
assert!(re.is_match(output.trim()), "Expected:\n{}\nGot:\n{}", re, output,);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -503,18 +486,9 @@ mod tests {
|
||||
eprint!("MAX_LOG_LEVEL={:?}", log::max_level());
|
||||
} else {
|
||||
assert_eq!("MAX_LOG_LEVEL=Info", run_test(None, None));
|
||||
assert_eq!(
|
||||
"MAX_LOG_LEVEL=Trace",
|
||||
run_test(Some("test=trace".into()), None)
|
||||
);
|
||||
assert_eq!(
|
||||
"MAX_LOG_LEVEL=Debug",
|
||||
run_test(Some("test=debug".into()), None)
|
||||
);
|
||||
assert_eq!(
|
||||
"MAX_LOG_LEVEL=Trace",
|
||||
run_test(None, Some("test=info".into()))
|
||||
);
|
||||
assert_eq!("MAX_LOG_LEVEL=Trace", run_test(Some("test=trace".into()), None));
|
||||
assert_eq!("MAX_LOG_LEVEL=Debug", run_test(Some("test=debug".into()), None));
|
||||
assert_eq!("MAX_LOG_LEVEL=Trace", run_test(None, Some("test=info".into())));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user