Skip to content

Commit 8e06705

Browse files
authored
Merge pull request #1731 from tursodatabase/logging-qol
Improve logging QOL
2 parents 64c4d22 + e9764bb commit 8e06705

5 files changed

Lines changed: 50 additions & 7 deletions

File tree

libsql-server/src/connection/mod.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ use tonic::metadata::BinaryMetadataValue;
1010

1111
use crate::auth::Authenticated;
1212
use crate::error::Error;
13+
use crate::http::user::timing::sample_time;
1314
use crate::metrics::{
1415
CONCURRENT_CONNECTIONS_COUNT, CONNECTION_ALIVE_DURATION, CONNECTION_CREATE_TIME,
1516
};
@@ -398,6 +399,7 @@ pub struct TrackedConnection<DB> {
398399

399400
impl<T> Drop for TrackedConnection<T> {
400401
fn drop(&mut self) {
402+
sample_time("connection-duration", self.created_at.elapsed());
401403
CONCURRENT_CONNECTIONS_COUNT.decrement(1.0);
402404
CONNECTION_ALIVE_DURATION.record(self.created_at.elapsed());
403405
}

libsql-server/src/http/admin/mod.rs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ struct AppState<C> {
4848
user_http_server: Arc<hrana::http::Server>,
4949
connector: C,
5050
metrics: Metrics,
51+
set_env_filter: Option<Box<dyn Fn(&str) -> anyhow::Result<()> + Sync + Send + 'static>>,
5152
}
5253

5354
impl<C> FromRef<Arc<AppState<C>>> for Metrics {
@@ -66,6 +67,7 @@ pub async fn run<A, C>(
6667
disable_metrics: bool,
6768
shutdown: Arc<Notify>,
6869
auth: Option<Arc<str>>,
70+
set_env_filter: Option<Box<dyn Fn(&str) -> anyhow::Result<()> + Sync + Send + 'static>>,
6971
) -> anyhow::Result<()>
7072
where
7173
A: crate::net::Accept,
@@ -167,11 +169,13 @@ where
167169
.route("/profile/heap/enable", post(enable_profile_heap))
168170
.route("/profile/heap/disable/:id", post(disable_profile_heap))
169171
.route("/profile/heap/:id", delete(delete_profile_heap))
172+
.route("/log-filter", post(handle_set_log_filter))
170173
.with_state(Arc::new(AppState {
171174
namespaces: namespaces.clone(),
172175
connector,
173176
user_http_server,
174177
metrics,
178+
set_env_filter,
175179
}))
176180
.layer(
177181
tower_http::trace::TraceLayer::new_for_http()
@@ -512,6 +516,16 @@ async fn handle_delete_namespace<C>(
512516
Ok(())
513517
}
514518

519+
async fn handle_set_log_filter<C>(
520+
State(app_state): State<Arc<AppState<C>>>,
521+
body: String,
522+
) -> crate::Result<()> {
523+
if let Some(ref cb) = app_state.set_env_filter {
524+
cb(&body)?;
525+
}
526+
Ok(())
527+
}
528+
515529
async fn handle_checkpoint<C>(
516530
State(app_state): State<Arc<AppState<C>>>,
517531
Path(namespace): Path<NamespaceName>,

libsql-server/src/http/user/timing.rs

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,13 +40,22 @@ macro_rules! record_time {
4040
let __ret__ = {
4141
$($rest)*
4242
};
43-
let _ = $crate::http::user::timing::TIMINGS.try_with(|t| t.record($k, __before__.elapsed()));
43+
let __elapsed__ = __before__.elapsed();
44+
tracing::debug!(target: "timings", name = $k, elapsed = tracing::field::debug(__elapsed__));
45+
let _ = $crate::http::user::timing::TIMINGS.try_with(|t| t.record($k, __elapsed__));
4446
__ret__
4547
}
4648
};
4749
}
4850

51+
pub fn sample_time(name: &'static str, duration: Duration) {
52+
tracing::debug!(target: "timings", name = name, elapsed = tracing::field::debug(duration));
53+
let _ = TIMINGS.try_with(|t| t.record(name, duration));
54+
}
55+
56+
#[tracing::instrument(skip_all, fields(req_id = tracing::field::debug(uuid::Uuid::new_v4())))]
4957
pub(crate) async fn timings_middleware<B>(request: Request<B>, next: Next<B>) -> Response {
58+
// tracing::error!("hello");
5059
TIMINGS
5160
.scope(Default::default(), async move {
5261
let mut response = record_time! {

libsql-server/src/lib.rs

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,7 @@ pub struct Server<C = HttpConnector, A = AddrIncoming, D = HttpsConnector<HttpCo
181181
pub should_sync_from_storage: bool,
182182
pub force_load_wals: bool,
183183
pub sync_conccurency: usize,
184+
pub set_log_level: Option<Box<dyn Fn(&str) -> anyhow::Result<()> + Send + Sync + 'static>>,
184185
}
185186

186187
impl<C, A, D> Default for Server<C, A, D> {
@@ -210,6 +211,7 @@ impl<C, A, D> Default for Server<C, A, D> {
210211
should_sync_from_storage: false,
211212
force_load_wals: false,
212213
sync_conccurency: 8,
214+
set_log_level: None,
213215
}
214216
}
215217
}
@@ -225,6 +227,7 @@ struct Services<A, P, S, C> {
225227
disable_default_namespace: bool,
226228
db_config: DbConfig,
227229
user_auth_strategy: Auth,
230+
pub set_log_level: Option<Box<dyn Fn(&str) -> anyhow::Result<()> + Send + Sync + 'static>>,
228231
}
229232

230233
struct TaskManager {
@@ -304,7 +307,7 @@ where
304307
S: ReplicationLog,
305308
C: Connector,
306309
{
307-
fn configure(self, task_manager: &mut TaskManager) {
310+
fn configure(mut self, task_manager: &mut TaskManager) {
308311
let user_http = UserApi {
309312
http_acceptor: self.user_api_config.http_acceptor,
310313
hrana_ws_acceptor: self.user_api_config.hrana_ws_acceptor,
@@ -339,6 +342,7 @@ where
339342
disable_metrics,
340343
shutdown,
341344
auth_key.map(Into::into),
345+
self.set_log_level.take(),
342346
)
343347
});
344348
}
@@ -538,7 +542,7 @@ where
538542
}
539543

540544
fn make_services<P: Proxy, L: ReplicationLog>(
541-
self,
545+
mut self,
542546
namespace_store: NamespaceStore,
543547
idle_shutdown_kicker: Option<IdleShutdownKicker>,
544548
proxy_service: P,
@@ -556,6 +560,7 @@ where
556560
disable_default_namespace: self.disable_default_namespace,
557561
db_config: self.db_config,
558562
user_auth_strategy,
563+
set_log_level: self.set_log_level.take(),
559564
}
560565
}
561566

libsql-server/src/main.rs

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
use std::env;
22
use std::net::SocketAddr;
33
use std::path::PathBuf;
4+
use std::str::FromStr;
45
use std::sync::Arc;
56

67
use anyhow::{bail, Context as _, Result};
@@ -10,9 +11,9 @@ use hyper::client::HttpConnector;
1011
use libsql_server::auth::{parse_http_basic_auth_arg, parse_jwt_keys, user_auth_strategies, Auth};
1112
use tokio::sync::Notify;
1213
use tokio::time::Duration;
13-
use tracing_subscriber::prelude::*;
1414
use tracing_subscriber::util::SubscriberInitExt;
1515
use tracing_subscriber::Layer;
16+
use tracing_subscriber::{prelude::*, EnvFilter};
1617

1718
use libsql_server::config::{
1819
AdminApiConfig, BottomlessConfig, DbConfig, HeartbeatConfig, MetaStoreConfig, RpcClientConfig,
@@ -641,7 +642,10 @@ fn make_meta_store_config(config: &Cli) -> anyhow::Result<MetaStoreConfig> {
641642
})
642643
}
643644

644-
async fn build_server(config: &Cli) -> anyhow::Result<Server> {
645+
async fn build_server(
646+
config: &Cli,
647+
set_log_level: impl Fn(&str) -> anyhow::Result<()> + Send + Sync + 'static,
648+
) -> anyhow::Result<Server> {
645649
let db_config = make_db_config(config)?;
646650
let user_api_config = make_user_api_config(config).await?;
647651
let admin_api_config = make_admin_api_config(config).await?;
@@ -709,6 +713,7 @@ async fn build_server(config: &Cli) -> anyhow::Result<Server> {
709713
should_sync_from_storage: config.sync_from_storage,
710714
force_load_wals: config.force_load_wals,
711715
sync_conccurency: config.sync_conccurency,
716+
set_log_level: Some(Box::new(set_log_level)),
712717
})
713718
}
714719

@@ -748,16 +753,24 @@ async fn main() -> Result<()> {
748753
#[cfg(feature = "debug-tools")]
749754
enable_libsql_logging();
750755

756+
let (filter, reload_handle) =
757+
tracing_subscriber::reload::Layer::new(tracing_subscriber::EnvFilter::from_default_env());
758+
let set_log_level = move |s: &str| -> anyhow::Result<()> {
759+
let filter = EnvFilter::from_str(s.trim())?;
760+
reload_handle.reload(filter)?;
761+
Ok(())
762+
};
763+
751764
registry
752765
.with(
753766
tracing_subscriber::fmt::layer()
754767
.with_ansi(false)
755-
.with_filter(tracing_subscriber::EnvFilter::from_default_env()),
768+
.with_filter(filter),
756769
)
757770
.init();
758771

759772
args.print_welcome_message();
760-
let server = build_server(&args).await?;
773+
let server = build_server(&args, set_log_level).await?;
761774
server.start().await?;
762775

763776
Ok(())

0 commit comments

Comments
 (0)