Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: configurable threshold and colorful output #6

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
145 changes: 145 additions & 0 deletions .idea/workspace.xml
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would you please remove this file?

Copy link
Author

@wathenjiang wathenjiang Jul 10, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah. I would do this, sorry for irrelevant file.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ parking_lot = "0.12"
pin-project = "1"
tokio = { version = "1", features = ["rt"] }
tracing = "0.1"
colored = "2"
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe we should hide this under a feature?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both LGTM :)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, both LGTM. They are about the balance between performance and convenience.


[dev-dependencies]
criterion = { version = "0.4", features = ["async", "async_tokio"] }
Expand Down
58 changes: 58 additions & 0 deletions examples/color.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
// Copyright 2023 RisingWave Labs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! This example shows how to configure warn threshold and color the warn


use std::time::Duration;
use await_tree::{Config, InstrumentAwait, Registry};
use tokio::time::sleep;

async fn short_work(){
sleep(Duration::from_millis(500)).instrument_await("short").await
}

async fn long_work(){
sleep(Duration::from_millis(5000)).instrument_await("long").await
}

#[tokio::main]
async fn main() {
let mut registry = Registry::new(Config{
verbose: true,
colored: true,
warn_threshold: Duration::from_millis(1000).into(),
});

let root = registry.register((), "work");
tokio::spawn(root.instrument(async {
short_work().await;
long_work().await;
}));

sleep(Duration::from_millis(100)).await;
let tree = registry.get(&()).unwrap().to_string();

// work
// short [105.606ms]
println!("{tree}");


sleep(Duration::from_millis(2000)).await;
let tree = registry.get(&()).unwrap().to_string();

// work
// long [1.609s]
println!("{tree}");
}
105 changes: 62 additions & 43 deletions src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,11 @@
// limitations under the License.

use std::fmt::{Debug, Write};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time;

use colored::Colorize;
use indextree::{Arena, NodeId};
use itertools::Itertools;
use parking_lot::{Mutex, MutexGuard};
Expand Down Expand Up @@ -57,50 +59,17 @@ pub struct Tree {

/// The current span node. This is the node that is currently being polled.
current: NodeId,

/// Whether to coloring the terminal
colored: bool,

/// if the time of execution is beyond it, warn it
warn_threshold: time::Duration,
Comment on lines +62 to +67
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What about directly storing a Config here?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What about directly storing a Config here?

If put Config here, the field verbose is not used by context.

Copy link
Member

@BugenZhao BugenZhao Jul 10, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, you're right. So I'm considering whether colored and warn_threshold should be properties of tree formatting, instead of the tree or the registry. 🤔 For example, we have...

struct FormatConfig {
  colored: bool,
  warn_threshold: time::Duration,
}

pub struct FormatTree<'a> {
  tree: &'a Tree,
  config: FormatConfig
}

impl Display for FormatTree<'_> { .. }

impl Tree {
  pub fn display(&self, config: FormatConfig) -> FormatTree<'_> { .. }
}

impl Display for Tree { /* delegate to `self.display(FormatConfig::default()).fmt(f)` */ }

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, It could be done this way.

}

impl std::fmt::Display for Tree {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
fn fmt_node(
f: &mut std::fmt::Formatter<'_>,
arena: &Arena<SpanNode>,
node: NodeId,
depth: usize,
current: NodeId,
) -> std::fmt::Result {
f.write_str(&" ".repeat(depth * 2))?;

let inner = arena[node].get();
f.write_str(inner.span.as_str())?;

let elapsed: std::time::Duration = inner.start_time.elapsed().into();
write!(
f,
" [{}{:.3?}]",
if depth > 0 && elapsed.as_secs() >= 10 {
"!!! "
} else {
""
},
elapsed
)?;

if depth > 0 && node == current {
f.write_str(" <== current")?;
}

f.write_char('\n')?;
for child in node
.children(arena)
.sorted_by_key(|&id| arena[id].get().start_time)
{
fmt_node(f, arena, child, depth + 1, current)?;
}

Ok(())
}

fmt_node(f, &self.arena, self.root, 0, self.current)?;
self.fmt_node(f, &self.arena, self.root, 0)?;

// Format all detached spans.
for node in self.arena.iter().filter(|n| !n.is_removed()) {
Expand All @@ -110,7 +79,7 @@ impl std::fmt::Display for Tree {
}
if node.parent().is_none() {
writeln!(f, "[Detached {id}]")?;
fmt_node(f, &self.arena, id, 1, self.current)?;
self.fmt_node(f, &self.arena, id, 1)?;
}
}

Expand Down Expand Up @@ -197,6 +166,54 @@ impl Tree {
pub(crate) fn current(&self) -> NodeId {
self.current
}

fn fmt_node(
&self,
f: &mut std::fmt::Formatter<'_>,
arena: &Arena<SpanNode>,
node: NodeId,
depth: usize,
) -> std::fmt::Result {
f.write_str(&" ".repeat(depth * 2))?;

let inner = arena[node].get();
f.write_str(inner.span.as_str())?;

let elapsed: time::Duration = inner.start_time.elapsed().into();

let elapsed_str = {
if depth == 0 {
"".to_string()
} else if elapsed.lt(&self.warn_threshold) {
format!(" [{:.3?}]", elapsed)
} else if self.colored {
format!(" [{:.3?}]", elapsed).red().to_string()
} else {
format!("!!! [{:.3?}]", elapsed)
}
};

write!(
f,
"{}",
elapsed_str
)?;

if depth > 0 && node == self.current {
f.write_str(" <== current")?;
}

f.write_char('\n')?;
for child in node
.children(arena)
.sorted_by_key(|&id| arena[id].get().start_time)
{
self.fmt_node(f, arena, child, depth + 1)?;
}

Ok(())
}

}

/// The task-local await-tree context.
Expand All @@ -214,7 +231,7 @@ pub struct TreeContext {

impl TreeContext {
/// Create a new context.
pub(crate) fn new(root_span: Span, verbose: bool) -> Self {
pub(crate) fn new(root_span: Span, verbose: bool, colored: bool, warn_threshold: time::Duration) -> Self {
static ID: AtomicU64 = AtomicU64::new(0);
let id = ID.fetch_add(1, Ordering::Relaxed);

Expand All @@ -225,6 +242,8 @@ impl TreeContext {
id,
verbose,
tree: Tree {
colored,
warn_threshold,
arena,
root,
current: root,
Expand Down
Loading