use crate::comm::ExecuteContext;
use crate::errors::{AkitaError, Result};
use crate::interceptor::blocking::AkitaInterceptor;
use crate::interceptor::logging::LoggingInterceptor;
use crate::interceptor::{InterceptorType, LogLevel, OperationType};
use crate::prelude::ExecuteResult;
use tracing::{debug, enabled, error, info, trace, warn, Level};
impl AkitaInterceptor for LoggingInterceptor {
fn before_execute(&self, ctx: &mut ExecuteContext) -> Result<()> {
if enabled!(target: "akita::sql", Level::DEBUG) {
debug!(
target: "akita::sql",
sql = %ctx.final_sql(),
params = ?ctx.final_params(),
"Preparing SQL"
);
}
if enabled!(target: "akita::sql", Level::TRACE) {
trace!(
target: "akita::sql",
connection_id = ?ctx.connection_id(),
"Start execution"
);
}
Ok(())
}
fn after_execute(
&self,
ctx: &mut ExecuteContext,
result: &mut Result<ExecuteResult>,
) -> Result<()> {
let duration_ms = ctx.start_time().elapsed().as_millis();
match result {
Err(err) => {
if enabled!(target: "akita::sql", Level::ERROR) {
error!(
target: "akita::sql",
error = %err,
sql = %ctx.final_sql(),
params = ?ctx.final_params(),
cost_ms = duration_ms as u64,
"SQL execution failed"
);
}
Ok(())
}
Ok(exec_result) => {
let rows = if *ctx.operation_type() == OperationType::Select {
exec_result.len()
} else {
ctx.metrics().rows_affected
};
if duration_ms > self.slow_query_threshold_ms as u128
&& enabled!(target: "akita::sql", Level::WARN)
{
warn!(
target: "akita::sql",
cost_ms = duration_ms as u64,
rows = rows,
sql = %ctx.final_sql(),
"Slow query detected"
);
}
if enabled!(target: "akita::sql", Level::INFO) {
info!(
target: "akita::sql",
cost_ms = duration_ms as u64,
rows = rows,
operation = ?ctx.operation_type(),
"SQL executed"
);
}
if enabled!(target: "akita::sql", Level::TRACE) {
trace!(
target: "akita::sql",
cost_ms = duration_ms as u64,
rows = rows,
sql = %ctx.final_sql(),
params = ?ctx.final_params(),
"Execution finished"
);
}
Ok(())
}
}
}
}