use super::*;
impl fmt::Write for PlainSanitizingWriter<'_> {
#[inline]
fn write_str(&mut self, s: &str) -> fmt::Result {
let Self { out } = self;
push_sanitized_plain(s, out);
Ok(())
}
}
impl fmt::Write for JsonSanitizingWriter<'_> {
#[inline]
fn write_str(&mut self, s: &str) -> fmt::Result {
let Self { out } = self;
push_sanitized_json(s, out);
Ok(())
}
}
impl Debug for LoggerConfig {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_struct(DEBUG_LOGGER_CONFIG)
.field(DEBUG_FIELD_LEVEL, &self.level)
.field(DEBUG_FIELD_FILE, &self.file)
.field(DEBUG_FIELD_CONSOLE, &self.console)
.field(DEBUG_FIELD_FORMAT, &self.format)
.field(DEBUG_FIELD_CHANNEL_CAPACITY, &self.channel_capacity)
.field(DEBUG_FIELD_HAS_SINK, &self.sink.is_some())
.finish()
}
}
impl Default for LoggerConfig {
fn default() -> Self {
Self {
level: LevelFilter::Info,
file: None,
console: true,
format: LogFormat::Plain,
channel_capacity: DEFAULT_LOGGER_CHANNEL_CAPACITY,
sink: None,
}
}
}
impl LoggerConfig {
pub fn new(level: LevelFilter) -> Self {
Self {
level,
..Self::default()
}
}
#[inline(always)]
pub fn get_level(&self) -> LevelFilter {
self.level
}
#[inline(always)]
pub fn get_file(&self) -> Option<&str> {
self.file.as_deref()
}
#[inline(always)]
pub fn get_console(&self) -> bool {
self.console
}
#[inline(always)]
pub fn get_format(&self) -> LogFormat {
self.format
}
#[inline(always)]
pub fn get_channel_capacity(&self) -> usize {
self.channel_capacity
}
pub fn set_level(&mut self, level: LevelFilter) -> &mut Self {
self.level = level;
self
}
pub fn set_file(&mut self, file: Option<String>) -> &mut Self {
self.file = file;
self
}
pub fn set_console(&mut self, enabled: bool) -> &mut Self {
self.console = enabled;
self
}
pub fn set_format(&mut self, format: LogFormat) -> &mut Self {
self.format = format;
self
}
pub fn set_channel_capacity(&mut self, capacity: usize) -> &mut Self {
self.channel_capacity = capacity.max(1);
self
}
pub fn set_sink(&mut self, sink: Option<Arc<dyn LogSink>>) -> &mut Self {
self.sink = sink;
self
}
pub fn with_level(mut self, level: LevelFilter) -> Self {
self.set_level(level);
self
}
pub fn with_file<P>(mut self, path: P) -> Self
where
P: Into<String>,
{
self.set_file(Some(path.into()));
self
}
pub fn with_console(mut self, enabled: bool) -> Self {
self.set_console(enabled);
self
}
pub fn with_format(mut self, format: LogFormat) -> Self {
self.set_format(format);
self
}
pub fn with_channel_capacity(mut self, capacity: usize) -> Self {
self.set_channel_capacity(capacity);
self
}
pub fn with_sink(mut self, sink: Arc<dyn LogSink>) -> Self {
self.set_sink(Some(sink));
self
}
}
impl log::Log for LoggerPlugin {
#[inline(always)]
fn enabled(&self, metadata: &Metadata<'_>) -> bool {
CONFIG
.get()
.is_none_or(|config: &LoggerConfig| metadata.level() <= config.get_level())
}
fn log(&self, record: &Record<'_>) {
let config_opt: Option<&LoggerConfig> = CONFIG.get();
if let Some(config) = config_opt
&& record.metadata().level() > config.get_level()
{
return;
}
let format: LogFormat = config_opt.map_or(LogFormat::Plain, LoggerConfig::get_format);
let console: bool = config_opt.is_none_or(LoggerConfig::get_console);
let sink: Option<&Arc<dyn LogSink>> =
config_opt.and_then(|c: &LoggerConfig| c.sink.as_ref());
let writer_tx: Option<&SyncSender<WriterCommand>> =
if config_opt.is_some_and(|c: &LoggerConfig| c.get_file().is_some()) {
WRITER_TX.get().and_then(Option::as_ref)
} else {
None
};
if !console && sink.is_none() && writer_tx.is_none() {
return;
}
let level_filter: LevelFilter = record.level().to_level_filter();
if let Some(tx) = writer_tx {
let mut line: String = String::with_capacity(128);
format_log_record_into(record, format, &mut line);
if let Some(custom_sink) = sink {
custom_sink.write_record(level_filter, &line);
}
if console {
line.push('\n');
let mut out: io::StdoutLock<'static> = stdout().lock();
let _: io::Result<()> = out.write_all(line.as_bytes());
let _: Option<char> = line.pop();
}
if tx.try_send(WriterCommand::Line(line)).is_err() {
DROPPED_RECORDS.fetch_add(1, Ordering::Relaxed);
}
return;
}
let dispatched: bool = LOG_LINE_BUF
.try_with(|cell: &RefCell<String>| {
if let Ok(mut buf) = cell.try_borrow_mut() {
buf.clear();
format_log_record_into(record, format, &mut buf);
if let Some(custom_sink) = sink {
custom_sink.write_record(level_filter, &buf);
}
if console {
buf.push('\n');
let mut out: io::StdoutLock<'static> = stdout().lock();
let _: io::Result<()> = out.write_all(buf.as_bytes());
}
if buf.capacity() > 4096 {
buf.clear();
buf.shrink_to(256);
}
true
} else {
false
}
})
.unwrap_or(false);
if !dispatched {
let mut line: String = String::with_capacity(128);
format_log_record_into(record, format, &mut line);
if let Some(custom_sink) = sink {
custom_sink.write_record(level_filter, &line);
}
if console {
line.push('\n');
let mut out: io::StdoutLock<'static> = stdout().lock();
let _: io::Result<()> = out.write_all(line.as_bytes());
}
}
}
fn flush(&self) {
if let Some(Some(tx)) = WRITER_TX.get() {
let (ack_tx, ack_rx): (SyncSender<()>, Receiver<()>) = sync_channel(1);
if tx.send(WriterCommand::Flush(ack_tx)).is_ok() {
let _: Result<(), RecvError> = ack_rx.recv();
}
}
if let Some(config) = CONFIG.get()
&& let Some(sink) = config.sink.as_ref()
{
sink.flush();
}
}
}
impl LoggerPlugin {
#[inline]
pub fn sanitize_log_text(input: &str) -> String {
let Some(start) = find_first_plain_unsafe(input.as_bytes()) else {
return input.to_owned();
};
let mut out: String = String::with_capacity(input.len() + 16);
push_sanitized_plain_from(input, start, &mut out);
out
}
pub fn init(config: LoggerConfig) -> Result<(), String> {
if CONFIG.get().is_some() {
return Err(ERROR_CONFIG_ALREADY_SET.to_owned());
}
if WRITER_TX.get().is_some() {
return Err(ERROR_FILE_ALREADY_SET.to_owned());
}
let writer_tx: Option<SyncSender<WriterCommand>> = match config.get_file() {
Some(path) => {
let file: File = OpenOptions::new()
.create(true)
.append(true)
.open(path)
.map_err(|error: io::Error| {
format!("the log file could not be opened: {error}")
})?;
Some(spawn_file_writer(file, config.get_channel_capacity())?)
}
None => None,
};
let level: LevelFilter = config.get_level();
set_logger(&LoggerPlugin)
.map_err(|_: SetLoggerError| ERROR_LOGGER_ALREADY_INSTALLED.to_owned())?;
WRITER_TX
.set(writer_tx)
.map_err(|_: Option<SyncSender<WriterCommand>>| ERROR_FILE_ALREADY_SET.to_owned())?;
CONFIG
.set(config)
.map_err(|_: LoggerConfig| ERROR_CONFIG_ALREADY_SET.to_owned())?;
set_max_level(level);
Ok(())
}
#[inline(always)]
pub fn get() -> Option<&'static LoggerConfig> {
CONFIG.get()
}
#[inline(always)]
pub fn dropped_count() -> u64 {
DROPPED_RECORDS.load(Ordering::Relaxed)
}
pub fn log_info<T>(data: T)
where
T: AsRef<str>,
{
log::info!("{}", data.as_ref());
}
pub fn log_error<T>(data: T)
where
T: AsRef<str>,
{
log::error!("{}", data.as_ref());
}
pub fn log_warn<T>(data: T)
where
T: AsRef<str>,
{
log::warn!("{}", data.as_ref());
}
pub fn log_debug<T>(data: T)
where
T: AsRef<str>,
{
log::debug!("{}", data.as_ref());
}
pub fn log_trace<T>(data: T)
where
T: AsRef<str>,
{
log::trace!("{}", data.as_ref());
}
}
impl ServerHook for RequestLogger {
#[inline(always)]
async fn new(_: &mut Stream, _: &mut Context) -> Self {
Self
}
async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
if CONFIG.get().is_none() || !log_enabled!(Level::Info) {
return Status::Continue;
}
ctx.set_attribute(ATTRIBUTE_STARTED_AT, Instant::now());
Status::Continue
}
}
impl ServerHook for ResponseLogger {
#[inline(always)]
async fn new(_: &mut Stream, _: &mut Context) -> Self {
Self
}
async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
if CONFIG.get().is_none() || !log_enabled!(Level::Info) {
return Status::Continue;
}
let started_at: Option<&Instant> = ctx.try_get_attribute_ref(ATTRIBUTE_STARTED_AT);
let elapsed: u128 = match started_at {
Some(started_at) => started_at.elapsed().as_millis(),
None => 0,
};
let method_text: &str = request_method_str(ctx.get_request().get_method());
let path: &str = ctx.get_request().get_path().as_str();
let status: usize = ctx.get_response().get_status_code();
log::info!(
"{} {} {} {}ms",
method_text,
if path.is_empty() { PATH_UNKNOWN } else { path },
status,
elapsed
);
Status::Continue
}
}