Skip to content

Commit

Permalink
feat: respect RUST_LOG (#316)
Browse files Browse the repository at this point in the history
* feat: respect RUST_LOG

* tests: get info logs for sqlx_pool
  • Loading branch information
chesedo authored Aug 30, 2022
1 parent a788b30 commit f37c9aa
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 3 deletions.
45 changes: 42 additions & 3 deletions service/src/logger.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use std::{collections::HashMap, env, str::FromStr};

use chrono::{DateTime, Utc};
use log::{Level, Metadata, Record};
use log::{Level, Metadata, ParseLevelError, Record};
use shuttle_common::{DeploymentId, LogItem};
use tokio::sync::mpsc::UnboundedSender;

Expand All @@ -13,17 +15,54 @@ pub struct Log {
pub struct Logger {
deployment_id: DeploymentId,
tx: UnboundedSender<Log>,
filter: HashMap<String, Level>,
}

impl Logger {
pub fn new(tx: UnboundedSender<Log>, deployment_id: DeploymentId) -> Self {
Self { tx, deployment_id }
let filter = if let Ok(rust_log) = env::var("RUST_LOG") {
let rust_log = rust_log
.split(',')
.map(|item| {
// Try to get target and level if both are set
if let Some((target, level)) = item.split_once('=') {
Result::<(String, Level), ParseLevelError>::Ok((
target.to_string(),
Level::from_str(level)?,
))
} else {
// Ok only target or level is set, but which is it
if let Ok(level) = Level::from_str(item) {
Ok((String::new(), level))
} else {
Ok((item.to_string(), Level::Trace))
}
}
})
.filter_map(Result::ok);

HashMap::from_iter(rust_log)
} else {
HashMap::from([(String::new(), Level::Error)])
};

Self {
tx,
deployment_id,
filter,
}
}
}

impl log::Log for Logger {
fn enabled(&self, metadata: &Metadata) -> bool {
metadata.level() <= Level::Info
for (target, level) in self.filter.iter() {
if metadata.target().starts_with(target) && &metadata.level() <= level {
return true;
}
}

false
}

fn log(&self, record: &Record) {
Expand Down
3 changes: 3 additions & 0 deletions service/tests/integration/loader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,9 @@ async fn sleep() {
async fn sqlx_pool() {
let loader = build_so_create_loader(RESOURCES_PATH, "sqlx-pool").unwrap();

// Make sure we'll get a log entry
std::env::set_var("RUST_LOG", "info");

// Don't initialize a pre-existing PostgresInstance here because the `PostgresInstance::wait_for_connectable()`
// code has `awaits` and we want to make sure they do not block inside `Service::build()`.
// At the same time we also want to test the PgPool is created on the correct runtime (ie does not cause a
Expand Down

0 comments on commit f37c9aa

Please sign in to comment.