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: add on_new_span impl to runtime Logger #864

Merged
merged 2 commits into from
May 5, 2023
Merged
Changes from all 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
55 changes: 50 additions & 5 deletions runtime/src/logger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ use prost_types::Timestamp;
use shuttle_common::tracing::JsonVisitor;
use shuttle_proto::runtime::{LogItem, LogLevel};
use tokio::sync::mpsc::UnboundedSender;
use tracing::Subscriber;
use tracing::{
span::{Attributes, Id},
Subscriber,
};
use tracing_subscriber::Layer;

pub struct Logger {
Expand All @@ -22,6 +25,41 @@ impl<S> Layer<S> for Logger
where
S: Subscriber,
{
fn on_new_span(
&self,
attrs: &Attributes,
_id: &Id,
_ctx: tracing_subscriber::layer::Context<'_, S>,
) {
let datetime = Utc::now();

let item = {
let metadata = attrs.metadata();
let mut visitor = JsonVisitor::default();

attrs.record(&mut visitor);

// Make the span name the log message
visitor.fields.insert(
"message".to_string(),
format!("[span] {}", metadata.name()).into(),
);

LogItem {
level: LogLevel::from(metadata.level()) as i32,
timestamp: Some(Timestamp::from(SystemTime::from(datetime))),
file: visitor.file.or_else(|| metadata.file().map(str::to_string)),
line: visitor.line.or_else(|| metadata.line()),
target: visitor
.target
.unwrap_or_else(|| metadata.target().to_string()),
fields: serde_json::to_vec(&visitor.fields).unwrap(),
}
};

self.tx.send(item).expect("sending log should succeed");
}

fn on_event(
&self,
event: &tracing::Event<'_>,
Expand Down Expand Up @@ -66,11 +104,18 @@ mod tests {

let _guard = tracing_subscriber::registry().with(logger).set_default();

tracing::debug!("this is");
tracing::info!("hi");
tracing::warn!("from");
tracing::error!("logger");
let span = tracing::debug_span!("this is a span");
span.in_scope(|| {
tracing::debug!("this is");
tracing::info!("hi");
tracing::warn!("from");
tracing::error!("logger");
});

assert_eq!(
r.blocking_recv().map(to_tuple),
Some(("[span] this is a span".to_string(), LogLevel::Debug as i32))
);
assert_eq!(
r.blocking_recv().map(to_tuple),
Some(("this is".to_string(), LogLevel::Debug as i32))
Expand Down