Remove manual log targets ()

This commit is contained in:
Rushmore Mushambi 2023-07-04 23:02:10 +02:00 committed by GitHub
parent 17455a4c24
commit 20ee2f1dc6
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
28 changed files with 128 additions and 215 deletions

View file

@ -71,9 +71,6 @@ use tokio::io::AsyncWrite;
#[cfg(not(target_arch = "wasm32"))]
use tokio::io::AsyncWriteExt;
#[cfg(not(target_arch = "wasm32"))]
const LOG: &str = "surrealdb::api::engine::local";
/// In-memory database
///
/// # Examples
@ -528,7 +525,7 @@ async fn router(
chn: channel::Sender<Vec<u8>>,
) -> std::result::Result<(), crate::Error> {
kvs.export(ns, db, chn).await.map_err(|error| {
error!(target: LOG, "{error}");
error!("{error}");
crate::Error::Db(error)
})
}

View file

@ -55,7 +55,6 @@ use tokio_util::compat::FuturesAsyncReadCompatExt;
use url::Url;
const SQL_PATH: &str = "sql";
const LOG: &str = "surrealdb::engine::remote::http";
/// The HTTP scheme used to connect to `http://` endpoints
#[derive(Debug)]
@ -167,7 +166,7 @@ async fn submit_auth(request: RequestBuilder) -> Result<Value> {
}
async fn query(request: RequestBuilder) -> Result<QueryResponse> {
info!(target: LOG, "{request:?}");
info!("{request:?}");
let response = request.send().await?.error_for_status()?;
let bytes = response.bytes().await?;
let responses = deserialize::<Vec<HttpQueryResponse>>(&bytes).map_err(|error| {

View file

@ -1,5 +1,4 @@
use super::Client;
use super::LOG;
use crate::api::conn::Connection;
use crate::api::conn::DbResponse;
use crate::api::conn::Method;
@ -68,7 +67,7 @@ impl Connection for Client {
) -> Pin<Box<dyn Future<Output = Result<Receiver<Result<DbResponse>>>> + Send + Sync + 'r>> {
Box::pin(async move {
let (sender, receiver) = flume::bounded(1);
trace!(target: LOG, "{param:?}");
trace!("{param:?}");
let route = Route {
request: (0, self.method, param),
response: sender,

View file

@ -36,7 +36,6 @@ use wasmtimer::tokio::Interval;
pub(crate) const PATH: &str = "rpc";
const PING_INTERVAL: Duration = Duration::from_secs(5);
const PING_METHOD: &str = "ping";
const LOG: &str = "surrealdb::engine::remote::ws";
/// The WS scheme used to connect to `ws://` endpoints
#[derive(Debug)]

View file

@ -1,4 +1,3 @@
use super::LOG;
use super::PATH;
use crate::api::conn::Connection;
use crate::api::conn::DbResponse;
@ -243,7 +242,7 @@ pub(crate) fn router(
request.insert("params".to_owned(), params.into());
}
let payload = Value::from(request);
trace!(target: LOG, "Request {payload}");
trace!("Request {payload}");
Message::Binary(payload.into())
};
if let Method::Authenticate
@ -268,7 +267,7 @@ pub(crate) fn router(
.await
.is_err()
{
trace!(target: LOG, "Receiver dropped");
trace!("Receiver dropped");
}
}
}
@ -276,7 +275,7 @@ pub(crate) fn router(
Err(error) => {
let error = Error::Ws(error.to_string());
if response.into_send_async(Err(error.into())).await.is_err() {
trace!(target: LOG, "Receiver dropped");
trace!("Receiver dropped");
}
break;
}
@ -288,7 +287,7 @@ pub(crate) fn router(
Ok(message) => match Response::try_from(&message) {
Ok(option) => {
if let Some(response) = option {
trace!(target: LOG, "{response:?}");
trace!("{response:?}");
if let Some(Ok(id)) =
response.id.map(Value::coerce_to_i64)
{
@ -327,10 +326,7 @@ pub(crate) fn router(
}
} else {
// Unfortunately, we don't know which response failed to deserialize
warn!(
target: LOG,
"Failed to deserialise message; {error:?}"
);
warn!("Failed to deserialise message; {error:?}");
}
}
}
@ -338,13 +334,10 @@ pub(crate) fn router(
Err(error) => {
match error {
WsError::ConnectionClosed => {
trace!(
target: LOG,
"Connection successfully closed on the server"
);
trace!("Connection successfully closed on the server");
}
error => {
trace!(target: LOG, "{error}");
trace!("{error}");
}
}
break;
@ -354,9 +347,9 @@ pub(crate) fn router(
Either::Ping => {
// only ping if we haven't talked to the server recently
if last_activity.elapsed() >= PING_INTERVAL {
trace!(target: LOG, "Pinging the server");
trace!("Pinging the server");
if let Err(error) = socket_sink.send(ping.clone()).await {
trace!(target: LOG, "failed to ping the server; {error:?}");
trace!("failed to ping the server; {error:?}");
break;
}
}
@ -369,13 +362,13 @@ pub(crate) fn router(
}
'reconnect: loop {
trace!(target: LOG, "Reconnecting...");
trace!("Reconnecting...");
match connect(&url, Some(config), maybe_connector.clone()).await {
Ok(s) => {
socket = s;
for (_, message) in &replay {
if let Err(error) = socket.send(message.clone()).await {
trace!(target: LOG, "{error}");
trace!("{error}");
time::sleep(time::Duration::from_secs(1)).await;
continue 'reconnect;
}
@ -389,18 +382,18 @@ pub(crate) fn router(
vec![key.as_str().into(), value.clone()].into(),
);
let payload = Value::from(request);
trace!(target: LOG, "Request {payload}");
trace!("Request {payload}");
if let Err(error) = socket.send(Message::Binary(payload.into())).await {
trace!(target: LOG, "{error}");
trace!("{error}");
time::sleep(time::Duration::from_secs(1)).await;
continue 'reconnect;
}
}
trace!(target: LOG, "Reconnected successfully");
trace!("Reconnected successfully");
break;
}
Err(error) => {
trace!(target: LOG, "Failed to reconnect; {error}");
trace!("Failed to reconnect; {error}");
time::sleep(time::Duration::from_secs(1)).await;
}
}
@ -413,7 +406,7 @@ impl Response {
fn try_from(message: &Message) -> Result<Option<Self>> {
match message {
Message::Text(text) => {
trace!(target: LOG, "Received an unexpected text message; {text}");
trace!("Received an unexpected text message; {text}");
Ok(None)
}
Message::Binary(binary) => deserialize(binary).map(Some).map_err(|error| {
@ -424,19 +417,19 @@ impl Response {
.into()
}),
Message::Ping(..) => {
trace!(target: LOG, "Received a ping from the server");
trace!("Received a ping from the server");
Ok(None)
}
Message::Pong(..) => {
trace!(target: LOG, "Received a pong from the server");
trace!("Received a pong from the server");
Ok(None)
}
Message::Frame(..) => {
trace!(target: LOG, "Received an unexpected raw frame");
trace!("Received an unexpected raw frame");
Ok(None)
}
Message::Close(..) => {
trace!(target: LOG, "Received an unexpected close message");
trace!("Received an unexpected close message");
Ok(None)
}
}
@ -450,9 +443,9 @@ impl Drop for Socket {
if let Some(mut conn) = mem::take(&mut self.0) {
futures::executor::block_on(async move {
match conn.borrow_mut().close().await {
Ok(..) => trace!(target: LOG, "Connection closed successfully"),
Ok(..) => trace!("Connection closed successfully"),
Err(error) => {
trace!(target: LOG, "Failed to close database connection; {error}")
trace!("Failed to close database connection; {error}")
}
}
});

View file

@ -1,4 +1,3 @@
use super::LOG;
use super::PATH;
use crate::api::conn::Connection;
use crate::api::conn::DbResponse;
@ -216,7 +215,7 @@ pub(crate) fn router(
request.insert("params".to_owned(), params.into());
}
let payload = Value::from(request);
trace!(target: LOG, "Request {payload}");
trace!("Request {payload}");
Message::Binary(payload.into())
};
if let Method::Authenticate
@ -241,7 +240,7 @@ pub(crate) fn router(
.await
.is_err()
{
trace!(target: LOG, "Receiver dropped");
trace!("Receiver dropped");
}
}
}
@ -249,7 +248,7 @@ pub(crate) fn router(
Err(error) => {
let error = Error::Ws(error.to_string());
if response.into_send_async(Err(error.into())).await.is_err() {
trace!(target: LOG, "Receiver dropped");
trace!("Receiver dropped");
}
break;
}
@ -260,7 +259,7 @@ pub(crate) fn router(
match Response::try_from(&message) {
Ok(option) => {
if let Some(response) = option {
trace!(target: LOG, "{response:?}");
trace!("{response:?}");
if let Some(Ok(id)) = response.id.map(Value::coerce_to_i64) {
if let Some((_method, sender)) = routes.remove(&id) {
let _res = sender
@ -290,10 +289,7 @@ pub(crate) fn router(
}
} else {
// Unfortunately, we don't know which response failed to deserialize
warn!(
target: LOG,
"Failed to deserialise message; {error:?}"
);
warn!("Failed to deserialise message; {error:?}");
}
}
}
@ -301,14 +297,14 @@ pub(crate) fn router(
}
Either::Event(event) => match event {
WsEvent::Error => {
trace!(target: LOG, "connection errored");
trace!("connection errored");
break;
}
WsEvent::WsErr(error) => {
trace!(target: LOG, "{error}");
trace!("{error}");
}
WsEvent::Closed(..) => {
trace!(target: LOG, "connection closed");
trace!("connection closed");
break;
}
_ => {}
@ -316,9 +312,9 @@ pub(crate) fn router(
Either::Ping => {
// only ping if we haven't talked to the server recently
if last_activity.elapsed() >= PING_INTERVAL {
trace!(target: LOG, "Pinging the server");
trace!("Pinging the server");
if let Err(error) = socket_sink.send(ping.clone()).await {
trace!(target: LOG, "failed to ping the server; {error:?}");
trace!("failed to ping the server; {error:?}");
break;
}
}
@ -330,7 +326,7 @@ pub(crate) fn router(
}
'reconnect: loop {
trace!(target: LOG, "Reconnecting...");
trace!("Reconnecting...");
match WsMeta::connect(&address.endpoint, None).await {
Ok((mut meta, stream)) => {
socket = stream;
@ -342,7 +338,7 @@ pub(crate) fn router(
match result {
Ok(events) => events,
Err(error) => {
trace!(target: LOG, "{error}");
trace!("{error}");
time::sleep(Duration::from_secs(1)).await;
continue 'reconnect;
}
@ -350,7 +346,7 @@ pub(crate) fn router(
};
for (_, message) in &replay {
if let Err(error) = socket.send(message.clone()).await {
trace!(target: LOG, "{error}");
trace!("{error}");
time::sleep(Duration::from_secs(1)).await;
continue 'reconnect;
}
@ -363,18 +359,18 @@ pub(crate) fn router(
vec![key.as_str().into(), value.clone()].into(),
);
let payload = Value::from(request);
trace!(target: LOG, "Request {payload}");
trace!("Request {payload}");
if let Err(error) = socket.send(Message::Binary(payload.into())).await {
trace!(target: LOG, "{error}");
trace!("{error}");
time::sleep(Duration::from_secs(1)).await;
continue 'reconnect;
}
}
trace!(target: LOG, "Reconnected successfully");
trace!("Reconnected successfully");
break;
}
Err(error) => {
trace!(target: LOG, "Failed to reconnect; {error}");
trace!("Failed to reconnect; {error}");
time::sleep(Duration::from_secs(1)).await;
}
}
@ -387,7 +383,7 @@ impl Response {
fn try_from(message: &Message) -> Result<Option<Self>> {
match message {
Message::Text(text) => {
trace!(target: LOG, "Received an unexpected text message; {text}");
trace!("Received an unexpected text message; {text}");
Ok(None)
}
Message::Binary(binary) => deserialize(binary).map(Some).map_err(|error| {

View file

@ -31,7 +31,6 @@ use wasm_bindgen_futures::spawn_local as spawn;
pub type Result<T> = std::result::Result<T, crate::Error>;
const SUPPORTED_VERSIONS: (&str, &str) = (">=1.0.0-beta.9, <2.0.0", "20230701.55918b7c");
const LOG: &str = "surrealdb::api";
/// Connection trait implemented by supported engines
pub trait Connection: conn::Connection {}
@ -153,13 +152,13 @@ where
Ok(version) => {
let server_build = &version.build;
if !req.matches(&version) {
warn!(target: LOG, "server version `{version}` does not match the range supported by the client `{versions}`");
warn!("server version `{version}` does not match the range supported by the client `{versions}`");
} else if !server_build.is_empty() && server_build < &build_meta {
warn!(target: LOG, "server build `{server_build}` is older than the minimum supported build `{build_meta}`");
warn!("server build `{server_build}` is older than the minimum supported build `{build_meta}`");
}
}
Err(error) => {
trace!(target: LOG, "failed to lookup the server version; {error:?}");
trace!("failed to lookup the server version; {error:?}");
}
}
});

View file

@ -5,7 +5,6 @@ use crate::dbs::Level;
use crate::dbs::Notification;
use crate::dbs::Options;
use crate::dbs::Transaction;
use crate::dbs::LOG;
use crate::dbs::{Auth, QueryType};
use crate::err::Error;
use crate::kvs::Datastore;
@ -171,7 +170,7 @@ impl<'a> Executor<'a> {
// Process all statements in query
for stm in qry.into_iter() {
// Log the statement
debug!(target: LOG, "Executing: {}", stm);
debug!("Executing: {}", stm);
// Reset errors
if self.txn.is_none() {
self.err = false;

View file

@ -2,7 +2,6 @@ use crate::ctx::Canceller;
use crate::ctx::Context;
use crate::dbs::Options;
use crate::dbs::Statement;
use crate::dbs::LOG;
use crate::doc::Document;
use crate::err::Error;
use crate::idx::planner::plan::Plan;
@ -78,7 +77,7 @@ impl Iterator {
stm: &Statement<'_>,
) -> Result<Value, Error> {
// Log the statement
trace!(target: LOG, "Iterating: {}", stm);
trace!("Iterating: {}", stm);
// Enable context override
let mut run = Context::new(ctx);
self.run = run.add_cancel();

View file

@ -36,5 +36,3 @@ pub mod cl;
#[cfg(test)]
pub(crate) mod test;
pub(crate) const LOG: &str = "surrealdb::dbs";

View file

@ -3,55 +3,30 @@
#[allow(clippy::module_inception)]
pub mod console {
// Specify the imports
use crate::fnc::script::LOG;
use crate::sql::value::Value;
use js::prelude::Rest;
/// Log the input values as INFO
pub fn log(args: Rest<Value>) {
info!(
target: LOG,
"{}",
args.iter().map(|v| v.to_raw_string()).collect::<Vec<String>>().join(" ")
);
info!("{}", args.iter().map(|v| v.to_raw_string()).collect::<Vec<String>>().join(" "));
}
/// Log the input values as INFO
pub fn info(args: Rest<Value>) {
info!(
target: LOG,
"{}",
args.iter().map(|v| v.to_raw_string()).collect::<Vec<String>>().join(" ")
);
info!("{}", args.iter().map(|v| v.to_raw_string()).collect::<Vec<String>>().join(" "));
}
/// Log the input values as WARN
pub fn warn(args: Rest<Value>) {
warn!(
target: LOG,
"{}",
args.iter().map(|v| v.to_raw_string()).collect::<Vec<String>>().join(" ")
);
warn!("{}", args.iter().map(|v| v.to_raw_string()).collect::<Vec<String>>().join(" "));
}
/// Log the input values as ERROR
pub fn error(args: Rest<Value>) {
error!(
target: LOG,
"{}",
args.iter().map(|v| v.to_raw_string()).collect::<Vec<String>>().join(" ")
);
error!("{}", args.iter().map(|v| v.to_raw_string()).collect::<Vec<String>>().join(" "));
}
/// Log the input values as DEBUG
pub fn debug(args: Rest<Value>) {
debug!(
target: LOG,
"{}",
args.iter().map(|v| v.to_raw_string()).collect::<Vec<String>>().join(" ")
);
debug!("{}", args.iter().map(|v| v.to_raw_string()).collect::<Vec<String>>().join(" "));
}
/// Log the input values as TRACE
pub fn trace(args: Rest<Value>) {
trace!(
target: LOG,
"{}",
args.iter().map(|v| v.to_raw_string()).collect::<Vec<String>>().join(" ")
);
trace!("{}", args.iter().map(|v| v.to_raw_string()).collect::<Vec<String>>().join(" "));
}
}

View file

@ -1,7 +1,5 @@
#![cfg(feature = "scripting")]
const LOG: &str = "surrealdb::jsr";
pub use main::run;
mod classes;

View file

@ -6,5 +6,4 @@ pub mod signup;
pub mod token;
pub mod verify;
pub const LOG: &str = "surrealdb::iam";
pub const TOKEN: &str = "Bearer ";

View file

@ -2,7 +2,6 @@ use crate::dbs::Auth;
use crate::dbs::Session;
use crate::err::Error;
use crate::iam::token::Claims;
use crate::iam::LOG;
use crate::iam::TOKEN;
use crate::kvs::Datastore;
use crate::sql::Algorithm;
@ -81,7 +80,7 @@ static DUD: Lazy<Validation> = Lazy::new(|| {
pub async fn token(kvs: &Datastore, session: &mut Session, auth: String) -> Result<(), Error> {
// Log the authentication type
trace!(target: LOG, "Attempting token authentication");
trace!("Attempting token authentication");
// Retrieve just the auth data
let auth = auth.trim_start_matches(TOKEN).trim();
// Decode the token without verifying
@ -91,14 +90,14 @@ pub async fn token(kvs: &Datastore, session: &mut Session, auth: String) -> Resu
// Check if the auth token can be used
if let Some(nbf) = token.claims.nbf {
if nbf > Utc::now().timestamp() {
trace!(target: LOG, "The 'nbf' field in the authentication token was invalid");
trace!("The 'nbf' field in the authentication token was invalid");
return Err(Error::InvalidAuth);
}
}
// Check if the auth token has expired
if let Some(exp) = token.claims.exp {
if exp < Utc::now().timestamp() {
trace!(target: LOG, "The 'exp' field in the authentication token was invalid");
trace!("The 'exp' field in the authentication token was invalid");
return Err(Error::InvalidAuth);
}
}
@ -114,7 +113,7 @@ pub async fn token(kvs: &Datastore, session: &mut Session, auth: String) -> Resu
..
} => {
// Log the decoded authentication claims
trace!(target: LOG, "Authenticating to scope `{}` with token `{}`", sc, tk);
trace!("Authenticating to scope `{}` with token `{}`", sc, tk);
// Create a new readonly transaction
let mut tx = kvs.transaction(false, false).await?;
// Parse the record id
@ -128,7 +127,7 @@ pub async fn token(kvs: &Datastore, session: &mut Session, auth: String) -> Resu
// Verify the token
decode::<Claims>(auth, &cf.0, &cf.1)?;
// Log the success
debug!(target: LOG, "Authenticated to scope `{}` with token `{}`", sc, tk);
debug!("Authenticated to scope `{}` with token `{}`", sc, tk);
// Set the session
session.sd = Some(id);
session.tk = Some(value);
@ -147,7 +146,7 @@ pub async fn token(kvs: &Datastore, session: &mut Session, auth: String) -> Resu
..
} => {
// Log the decoded authentication claims
trace!(target: LOG, "Authenticating to scope `{}`", sc);
trace!("Authenticating to scope `{}`", sc);
// Create a new readonly transaction
let mut tx = kvs.transaction(false, false).await?;
// Parse the record id
@ -158,7 +157,7 @@ pub async fn token(kvs: &Datastore, session: &mut Session, auth: String) -> Resu
// Verify the token
decode::<Claims>(auth, &cf.0, &cf.1)?;
// Log the success
debug!(target: LOG, "Authenticated to scope `{}`", sc);
debug!("Authenticated to scope `{}`", sc);
// Set the session
session.tk = Some(value);
session.ns = Some(ns.to_owned());
@ -176,7 +175,7 @@ pub async fn token(kvs: &Datastore, session: &mut Session, auth: String) -> Resu
..
} => {
// Log the decoded authentication claims
trace!(target: LOG, "Authenticating to database `{}` with token `{}`", db, tk);
trace!("Authenticating to database `{}` with token `{}`", db, tk);
// Create a new readonly transaction
let mut tx = kvs.transaction(false, false).await?;
// Get the database token
@ -185,7 +184,7 @@ pub async fn token(kvs: &Datastore, session: &mut Session, auth: String) -> Resu
// Verify the token
decode::<Claims>(auth, &cf.0, &cf.1)?;
// Log the success
debug!(target: LOG, "Authenticated to database `{}` with token `{}`", db, tk);
debug!("Authenticated to database `{}` with token `{}`", db, tk);
// Set the session
session.tk = Some(value);
session.ns = Some(ns.to_owned());
@ -201,7 +200,7 @@ pub async fn token(kvs: &Datastore, session: &mut Session, auth: String) -> Resu
..
} => {
// Log the decoded authentication claims
trace!(target: LOG, "Authenticating to database `{}` with login `{}`", db, id);
trace!("Authenticating to database `{}` with login `{}`", db, id);
// Create a new readonly transaction
let mut tx = kvs.transaction(false, false).await?;
// Get the database login
@ -210,7 +209,7 @@ pub async fn token(kvs: &Datastore, session: &mut Session, auth: String) -> Resu
// Verify the token
decode::<Claims>(auth, &cf.0, &cf.1)?;
// Log the success
debug!(target: LOG, "Authenticated to database `{}` with login `{}`", db, id);
debug!("Authenticated to database `{}` with login `{}`", db, id);
// Set the session
session.tk = Some(value);
session.ns = Some(ns.to_owned());
@ -225,7 +224,7 @@ pub async fn token(kvs: &Datastore, session: &mut Session, auth: String) -> Resu
..
} => {
// Log the decoded authentication claims
trace!(target: LOG, "Authenticating to namespace `{}` with token `{}`", ns, tk);
trace!("Authenticating to namespace `{}` with token `{}`", ns, tk);
// Create a new readonly transaction
let mut tx = kvs.transaction(false, false).await?;
// Get the namespace token
@ -234,7 +233,7 @@ pub async fn token(kvs: &Datastore, session: &mut Session, auth: String) -> Resu
// Verify the token
decode::<Claims>(auth, &cf.0, &cf.1)?;
// Log the success
trace!(target: LOG, "Authenticated to namespace `{}` with token `{}`", ns, tk);
trace!("Authenticated to namespace `{}` with token `{}`", ns, tk);
// Set the session
session.tk = Some(value);
session.ns = Some(ns.to_owned());
@ -248,7 +247,7 @@ pub async fn token(kvs: &Datastore, session: &mut Session, auth: String) -> Resu
..
} => {
// Log the decoded authentication claims
trace!(target: LOG, "Authenticating to namespace `{}` with login `{}`", ns, id);
trace!("Authenticating to namespace `{}` with login `{}`", ns, id);
// Create a new readonly transaction
let mut tx = kvs.transaction(false, false).await?;
// Get the namespace login
@ -257,7 +256,7 @@ pub async fn token(kvs: &Datastore, session: &mut Session, auth: String) -> Resu
// Verify the token
decode::<Claims>(auth, &cf.0, &cf.1)?;
// Log the success
trace!(target: LOG, "Authenticated to namespace `{}` with login `{}`", ns, id);
trace!("Authenticated to namespace `{}` with login `{}`", ns, id);
// Set the session
session.tk = Some(value);
session.ns = Some(ns.to_owned());

View file

@ -8,7 +8,6 @@ use crate::dbs::Response;
use crate::dbs::Session;
use crate::dbs::Variables;
use crate::err::Error;
use crate::kvs::LOG;
use crate::sql;
use crate::sql::Query;
use crate::sql::Value;
@ -112,9 +111,9 @@ impl Datastore {
"memory" => {
#[cfg(feature = "kv-mem")]
{
info!(target: LOG, "Starting kvs store in {}", path);
info!("Starting kvs store in {}", path);
let v = super::mem::Datastore::new().await.map(Inner::Mem);
info!(target: LOG, "Started kvs store in {}", path);
info!("Started kvs store in {}", path);
v
}
#[cfg(not(feature = "kv-mem"))]
@ -124,11 +123,11 @@ impl Datastore {
s if s.starts_with("file:") => {
#[cfg(feature = "kv-rocksdb")]
{
info!(target: LOG, "Starting kvs store at {}", path);
info!("Starting kvs store at {}", path);
let s = s.trim_start_matches("file://");
let s = s.trim_start_matches("file:");
let v = super::rocksdb::Datastore::new(s).await.map(Inner::RocksDB);
info!(target: LOG, "Started kvs store at {}", path);
info!("Started kvs store at {}", path);
v
}
#[cfg(not(feature = "kv-rocksdb"))]
@ -138,11 +137,11 @@ impl Datastore {
s if s.starts_with("rocksdb:") => {
#[cfg(feature = "kv-rocksdb")]
{
info!(target: LOG, "Starting kvs store at {}", path);
info!("Starting kvs store at {}", path);
let s = s.trim_start_matches("rocksdb://");
let s = s.trim_start_matches("rocksdb:");
let v = super::rocksdb::Datastore::new(s).await.map(Inner::RocksDB);
info!(target: LOG, "Started kvs store at {}", path);
info!("Started kvs store at {}", path);
v
}
#[cfg(not(feature = "kv-rocksdb"))]
@ -152,11 +151,11 @@ impl Datastore {
s if s.starts_with("speedb:") => {
#[cfg(feature = "kv-speedb")]
{
info!(target: LOG, "Starting kvs store at {}", path);
info!("Starting kvs store at {}", path);
let s = s.trim_start_matches("speedb://");
let s = s.trim_start_matches("speedb:");
let v = super::speedb::Datastore::new(s).await.map(Inner::SpeeDB);
info!(target: LOG, "Started kvs store at {}", path);
info!("Started kvs store at {}", path);
v
}
#[cfg(not(feature = "kv-speedb"))]
@ -166,11 +165,11 @@ impl Datastore {
s if s.starts_with("indxdb:") => {
#[cfg(feature = "kv-indxdb")]
{
info!(target: LOG, "Starting kvs store at {}", path);
info!("Starting kvs store at {}", path);
let s = s.trim_start_matches("indxdb://");
let s = s.trim_start_matches("indxdb:");
let v = super::indxdb::Datastore::new(s).await.map(Inner::IndxDB);
info!(target: LOG, "Started kvs store at {}", path);
info!("Started kvs store at {}", path);
v
}
#[cfg(not(feature = "kv-indxdb"))]
@ -180,11 +179,11 @@ impl Datastore {
s if s.starts_with("tikv:") => {
#[cfg(feature = "kv-tikv")]
{
info!(target: LOG, "Connecting to kvs store at {}", path);
info!("Connecting to kvs store at {}", path);
let s = s.trim_start_matches("tikv://");
let s = s.trim_start_matches("tikv:");
let v = super::tikv::Datastore::new(s).await.map(Inner::TiKV);
info!(target: LOG, "Connected to kvs store at {}", path);
info!("Connected to kvs store at {}", path);
v
}
#[cfg(not(feature = "kv-tikv"))]
@ -194,11 +193,11 @@ impl Datastore {
s if s.starts_with("fdb:") => {
#[cfg(feature = "kv-fdb")]
{
info!(target: LOG, "Connecting to kvs store at {}", path);
info!("Connecting to kvs store at {}", path);
let s = s.trim_start_matches("fdb://");
let s = s.trim_start_matches("fdb:");
let v = super::fdb::Datastore::new(s).await.map(Inner::FoundationDB);
info!(target: LOG, "Connected to kvs store at {}", path);
info!("Connected to kvs store at {}", path);
v
}
#[cfg(not(feature = "kv-fdb"))]
@ -206,7 +205,7 @@ impl Datastore {
}
// The datastore path is not valid
_ => {
info!(target: LOG, "Unable to load the specified datastore {}", path);
info!("Unable to load the specified datastore {}", path);
Err(Error::Ds("Unable to load the specified datastore".into()))
}
};

View file

@ -29,5 +29,3 @@ mod tests;
pub use self::ds::*;
pub use self::kv::*;
pub use self::tx::*;
pub(crate) const LOG: &str = "surrealdb::kvs";

View file

@ -35,9 +35,6 @@ use std::ops::Range;
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};
#[cfg(debug_assertions)]
const LOG: &str = "surrealdb::txn";
/// A set of undoable updates and requests against a dataset.
#[allow(dead_code)]
pub struct Transaction {
@ -96,7 +93,7 @@ impl Transaction {
/// in a [`Error::TxFinished`] error.
pub async fn closed(&self) -> bool {
#[cfg(debug_assertions)]
trace!(target: LOG, "Closed");
trace!("Closed");
match self {
#[cfg(feature = "kv-mem")]
Transaction {
@ -138,7 +135,7 @@ impl Transaction {
/// This reverses all changes made within the transaction.
pub async fn cancel(&mut self) -> Result<(), Error> {
#[cfg(debug_assertions)]
trace!(target: LOG, "Cancel");
trace!("Cancel");
match self {
#[cfg(feature = "kv-mem")]
Transaction {
@ -180,7 +177,7 @@ impl Transaction {
/// This attempts to commit all changes made within the transaction.
pub async fn commit(&mut self) -> Result<(), Error> {
#[cfg(debug_assertions)]
trace!(target: LOG, "Commit");
trace!("Commit");
match self {
#[cfg(feature = "kv-mem")]
Transaction {
@ -224,7 +221,7 @@ impl Transaction {
K: Into<Key> + Debug,
{
#[cfg(debug_assertions)]
trace!(target: LOG, "Del {:?}", key);
trace!("Del {:?}", key);
match self {
#[cfg(feature = "kv-mem")]
Transaction {
@ -268,7 +265,7 @@ impl Transaction {
K: Into<Key> + Debug,
{
#[cfg(debug_assertions)]
trace!(target: LOG, "Exi {:?}", key);
trace!("Exi {:?}", key);
match self {
#[cfg(feature = "kv-mem")]
Transaction {
@ -312,7 +309,7 @@ impl Transaction {
K: Into<Key> + Debug,
{
#[cfg(debug_assertions)]
trace!(target: LOG, "Get {:?}", key);
trace!("Get {:?}", key);
match self {
#[cfg(feature = "kv-mem")]
Transaction {
@ -357,7 +354,7 @@ impl Transaction {
V: Into<Val> + Debug,
{
#[cfg(debug_assertions)]
trace!(target: LOG, "Set {:?} => {:?}", key, val);
trace!("Set {:?} => {:?}", key, val);
match self {
#[cfg(feature = "kv-mem")]
Transaction {
@ -402,7 +399,7 @@ impl Transaction {
V: Into<Val> + Debug,
{
#[cfg(debug_assertions)]
trace!(target: LOG, "Put {:?} => {:?}", key, val);
trace!("Put {:?} => {:?}", key, val);
match self {
#[cfg(feature = "kv-mem")]
Transaction {
@ -448,7 +445,7 @@ impl Transaction {
K: Into<Key> + Debug,
{
#[cfg(debug_assertions)]
trace!(target: LOG, "Scan {:?} - {:?}", rng.start, rng.end);
trace!("Scan {:?} - {:?}", rng.start, rng.end);
match self {
#[cfg(feature = "kv-mem")]
Transaction {
@ -493,7 +490,7 @@ impl Transaction {
V: Into<Val> + Debug,
{
#[cfg(debug_assertions)]
trace!(target: LOG, "Putc {:?} if {:?} => {:?}", key, chk, val);
trace!("Putc {:?} if {:?} => {:?}", key, chk, val);
match self {
#[cfg(feature = "kv-mem")]
Transaction {
@ -538,7 +535,7 @@ impl Transaction {
V: Into<Val> + Debug,
{
#[cfg(debug_assertions)]
trace!(target: LOG, "Delc {:?} if {:?}", key, chk);
trace!("Delc {:?} if {:?}", key, chk);
match self {
#[cfg(feature = "kv-mem")]
Transaction {

View file

@ -1,7 +1,6 @@
use crate::cli::abstraction::{
AuthArguments, DatabaseConnectionArguments, DatabaseSelectionArguments,
};
use crate::cli::LOG;
use crate::err::Error;
use clap::Args;
use surrealdb::engine::any::connect;
@ -57,7 +56,7 @@ pub async fn init(
client.use_ns(ns).use_db(db).await?;
// Export the data from the database
client.export(file).await?;
info!(target: LOG, "The SQL file was exported successfully");
info!("The SQL file was exported successfully");
// Everything OK
Ok(())
}

View file

@ -1,7 +1,6 @@
use crate::cli::abstraction::{
AuthArguments, DatabaseConnectionArguments, DatabaseSelectionArguments,
};
use crate::cli::LOG;
use crate::err::Error;
use clap::Args;
use surrealdb::engine::any::connect;
@ -55,7 +54,7 @@ pub async fn init(
client.use_ns(ns).use_db(db).await?;
// Import the data into the database
client.import(file).await?;
info!(target: LOG, "The SQL file was imported successfully");
info!("The SQL file was imported successfully");
// Everything OK
Ok(())
}

View file

@ -25,8 +25,6 @@ use sql::SqlCommandArguments;
use start::StartCommandArguments;
use std::process::ExitCode;
pub const LOG: &str = "surrealdb::cli";
const INFO: &str = "
To get started using SurrealDB, and for guides on connecting to and building applications
on top of SurrealDB, check out the SurrealDB documentation (https://surrealdb.com/docs).
@ -88,7 +86,7 @@ pub async fn init() -> ExitCode {
Commands::IsReady(args) => isready::init(args).await,
};
if let Err(e) = output {
error!(target: LOG, "{}", e);
error!("{}", e);
ExitCode::FAILURE
} else {
ExitCode::SUCCESS

View file

@ -8,8 +8,6 @@ use surrealdb::kvs::Datastore;
pub static DB: OnceCell<Datastore> = OnceCell::new();
const LOG: &str = "surrealdb::dbs";
#[derive(Args, Debug)]
pub struct StartCommandDbsOptions {
#[arg(help = "The maximum duration of any query")]
@ -27,8 +25,8 @@ pub async fn init(
let opt = CF.get().unwrap();
// Log authentication options
match opt.strict {
true => info!(target: LOG, "Database strict mode is enabled"),
false => info!(target: LOG, "Database strict mode is disabled"),
true => info!("Database strict mode is enabled"),
false => info!("Database strict mode is disabled"),
};
// Parse and setup the desired kv datastore
let dbs = Datastore::new(&opt.path).await?.query_timeout(query_timeout);

5
src/env/mod.rs vendored
View file

@ -3,13 +3,10 @@ use crate::cnf::PKG_VERSION;
use crate::err::Error;
use surrealdb::env::{arch, os};
#[cfg(feature = "has-storage")]
const LOG: &str = "surrealdb::env";
#[cfg(feature = "has-storage")]
pub async fn init() -> Result<(), Error> {
// Log version
info!(target: LOG, "Running {}", release());
info!("Running {}", release());
// All ok
Ok(())
}

View file

@ -2,7 +2,6 @@ pub mod verify;
use crate::cli::CF;
use crate::err::Error;
use surrealdb::iam::LOG;
pub const BASIC: &str = "Basic ";
@ -12,10 +11,10 @@ pub async fn init() -> Result<(), Error> {
// Log authentication options
match opt.pass {
Some(_) => {
info!(target: LOG, "Root authentication is enabled");
info!(target: LOG, "Root username is '{}'", opt.user);
info!("Root authentication is enabled");
info!("Root username is '{}'", opt.user);
}
None => info!(target: LOG, "Root authentication is disabled"),
None => info!("Root authentication is disabled"),
};
// All ok
Ok(())

View file

@ -8,11 +8,10 @@ use std::sync::Arc;
use surrealdb::dbs::Auth;
use surrealdb::dbs::Session;
use surrealdb::iam::base::{Engine, BASE64};
use surrealdb::iam::LOG;
pub async fn basic(session: &mut Session, auth: String) -> Result<(), Error> {
// Log the authentication type
trace!(target: LOG, "Attempting basic authentication");
trace!("Attempting basic authentication");
// Retrieve just the auth data
let auth = auth.trim_start_matches(BASIC).trim();
// Get a database reference
@ -33,7 +32,7 @@ pub async fn basic(session: &mut Session, auth: String) -> Result<(), Error> {
if let Some(root) = &opts.pass {
if user == opts.user && pass == root {
// Log the authentication type
debug!(target: LOG, "Authenticated as super user");
debug!("Authenticated as super user");
// Store the authentication data
session.au = Arc::new(Auth::Kv);
return Ok(());
@ -49,7 +48,7 @@ pub async fn basic(session: &mut Session, auth: String) -> Result<(), Error> {
let hash = PasswordHash::new(&nl.hash).unwrap();
if Argon2::default().verify_password(pass.as_ref(), &hash).is_ok() {
// Log the successful namespace authentication
debug!(target: LOG, "Authenticated as namespace user: {}", user);
debug!("Authenticated as namespace user: {}", user);
// Store the authentication data
session.au = Arc::new(Auth::Ns(ns.to_owned()));
return Ok(());
@ -63,7 +62,7 @@ pub async fn basic(session: &mut Session, auth: String) -> Result<(), Error> {
let hash = PasswordHash::new(&dl.hash).unwrap();
if Argon2::default().verify_password(pass.as_ref(), &hash).is_ok() {
// Log the successful namespace authentication
debug!(target: LOG, "Authenticated as database user: {}", user);
debug!("Authenticated as database user: {}", user);
// Store the authentication data
session.au = Arc::new(Auth::Db(ns.to_owned(), db.to_owned()));
return Ok(());

View file

@ -13,12 +13,9 @@ impl<T: fmt::Display> fmt::Display for OptFmt<T> {
}
}
const NAME: &str = "surrealdb::net";
pub fn write() -> warp::filters::log::Log<impl Fn(warp::filters::log::Info) + Copy> {
warp::log::custom(|info| {
event!(
target: NAME,
Level::INFO,
"{} {} {} {:?} {} \"{}\" {:?}",
OptFmt(info.remote_addr()),

View file

@ -24,8 +24,6 @@ use crate::cli::CF;
use crate::err::Error;
use warp::Filter;
const LOG: &str = "surrealdb::net";
pub async fn init() -> Result<(), Error> {
// Setup web routes
let net = index::config()
@ -69,7 +67,7 @@ pub async fn init() -> Result<(), Error> {
// Get local copy of options
let opt = CF.get().unwrap();
info!(target: LOG, "Starting web server on {}", &opt.bind);
info!("Starting web server on {}", &opt.bind);
if let (Some(c), Some(k)) = (&opt.crt, &opt.key) {
// Bind the server to the desired port
@ -80,27 +78,27 @@ pub async fn init() -> Result<(), Error> {
.bind_with_graceful_shutdown(opt.bind, async move {
// Capture the shutdown signals and log that the graceful shutdown has started
let result = signals::listen().await.expect("Failed to listen to shutdown signal");
info!(target: LOG, "{} received. Start graceful shutdown...", result);
info!("{} received. Start graceful shutdown...", result);
});
// Log the server startup status
info!(target: LOG, "Started web server on {}", &adr);
info!("Started web server on {}", &adr);
// Run the server forever
srv.await;
// Log the server shutdown event
info!(target: LOG, "Shutdown complete. Bye!")
info!("Shutdown complete. Bye!")
} else {
// Bind the server to the desired port
let (adr, srv) = warp::serve(net).bind_with_graceful_shutdown(opt.bind, async move {
// Capture the shutdown signals and log that the graceful shutdown has started
let result = signals::listen().await.expect("Failed to listen to shutdown signal");
info!(target: LOG, "{} received. Start graceful shutdown...", result);
info!("{} received. Start graceful shutdown...", result);
});
// Log the server startup status
info!(target: LOG, "Started web server on {}", &adr);
info!("Started web server on {}", &adr);
// Run the server forever
srv.await;
// Log the server shutdown event
info!(target: LOG, "Shutdown complete. Bye!")
info!("Shutdown complete. Bye!")
};
Ok(())

View file

@ -6,7 +6,6 @@ use crate::cnf::WEBSOCKET_PING_FREQUENCY;
use crate::dbs::DB;
use crate::err::Error;
use crate::net::session;
use crate::net::LOG;
use crate::rpc::args::Take;
use crate::rpc::paths::{ID, METHOD, PARAMS};
use crate::rpc::res;
@ -114,7 +113,7 @@ impl Rpc {
// Send the message to the client
if let Err(err) = wtx.send(res).await {
// Output the WebSocket error to the logs
trace!(target: LOG, "WebSocket error: {:?}", err);
trace!("WebSocket error: {:?}", err);
// It's already failed, so ignore error
let _ = wtx.close().await;
// Exit out of the loop
@ -127,7 +126,7 @@ impl Rpc {
tokio::task::spawn(async move {
let rpc = moved_rpc;
while let Ok(v) = DB.get().unwrap().notifications().recv().await {
trace!(target: LOG, "Received notification: {:?}", v);
trace!("Received notification: {:?}", v);
// Find which websocket the notification belongs to
match LIVE_QUERIES.read().await.get(&v.id) {
Some(ws_id) => {
@ -137,8 +136,8 @@ impl Rpc {
match ws_write.get(ws_id) {
None => {
error!(
target: LOG,
"Tracked WebSocket {:?} not found for lq: {:?}", ws_id, &v.id
"Tracked WebSocket {:?} not found for lq: {:?}",
ws_id, &v.id
);
}
Some(ws_sender) => {
@ -146,7 +145,6 @@ impl Rpc {
.send(rpc.read().await.format.clone(), ws_sender.clone())
.await;
trace!(
target: LOG,
"Sent notification to WebSocket {:?} for lq: {:?}",
ws_id,
&v.id
@ -155,7 +153,7 @@ impl Rpc {
}
}
None => {
error!(target: LOG, "Unknown websocket for live query: {:?}", v.id);
error!("Unknown websocket for live query: {:?}", v.id);
}
}
}
@ -187,7 +185,7 @@ impl Rpc {
// There was an error receiving the message
Err(err) => {
// Output the WebSocket error to the logs
trace!(target: LOG, "WebSocket error: {:?}", err);
trace!("WebSocket error: {:?}", err);
// Exit out of the loop
break;
}
@ -201,7 +199,7 @@ impl Rpc {
// Fetch the unique id of the WebSocket
let id = rpc.read().await.uuid;
// Log that the WebSocket has connected
trace!(target: LOG, "WebSocket {} connected", id);
trace!("WebSocket {} connected", id);
// Store this WebSocket in the list of WebSockets
WEBSOCKETS.write().await.insert(id, chn);
}
@ -210,7 +208,7 @@ impl Rpc {
// Fetch the unique id of the WebSocket
let id = rpc.read().await.uuid;
// Log that the WebSocket has disconnected
trace!(target: LOG, "WebSocket {} disconnected", id);
trace!("WebSocket {} disconnected", id);
// Remove this WebSocket from the list of WebSockets
WEBSOCKETS.write().await.remove(&id);
// Remove all live queries
@ -218,7 +216,7 @@ impl Rpc {
let mut live_query_to_gc: Vec<Uuid> = vec![];
for (key, value) in locked_lq_map.iter() {
if value == &id {
trace!(target: LOG, "Removing live query: {}", key);
trace!("Removing live query: {}", key);
live_query_to_gc.push(*key);
}
}
@ -258,7 +256,7 @@ impl Rpc {
_ => return res::failure(None, Failure::INTERNAL_ERROR).send(out, chn).await,
};
// Log the received request
trace!(target: LOG, "RPC Received: {}", req);
trace!("RPC Received: {}", req);
// Fetch the 'id' argument
let id = match req.pick(&*ID) {
v if v.is_none() => None,
@ -742,24 +740,14 @@ impl Rpc {
if let Ok(Value::Uuid(lqid)) = &res.result {
// Match on Uuid type
LIVE_QUERIES.write().await.insert(lqid.0, self.uuid);
trace!(
target: LOG,
"Registered live query {} on websocket {}",
lqid,
self.uuid
);
trace!("Registered live query {} on websocket {}", lqid, self.uuid);
}
}
QueryType::Kill => {
if let Ok(Value::Uuid(lqid)) = &res.result {
let ws_id = LIVE_QUERIES.write().await.remove(&lqid.0);
if let Some(ws_id) = ws_id {
trace!(
target: LOG,
"Unregistered live query {} on websocket {}",
lqid,
ws_id
);
trace!("Unregistered live query {} on websocket {}", lqid, ws_id);
}
}
}

View file

@ -9,8 +9,6 @@ use surrealdb::sql::Value;
use tracing::instrument;
use warp::ws::Message;
const LOG: &str = "surrealdb::rpc::res";
#[derive(Clone)]
pub enum Output {
Json, // JSON
@ -105,7 +103,7 @@ impl Response {
}
};
let _ = chn.send(message).await;
trace!(target: LOG, "Response sent");
trace!("Response sent");
}
}