use super::*;
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()
}
}
pub fn get_level(&self) -> LevelFilter {
self.level
}
pub fn get_file(&self) -> Option<&str> {
self.file.as_deref()
}
pub fn get_console(&self) -> bool {
self.console
}
pub fn get_format(&self) -> LogFormat {
self.format
}
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<SharedLogSink>) -> &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: SharedLogSink) -> Self {
self.set_sink(Some(sink));
self
}
}
impl log::Log for LoggerPlugin {
fn enabled(&self, metadata: &Metadata<'_>) -> bool {
CONFIG
.get()
.is_none_or(|config: &LoggerConfig| metadata.level() <= config.get_level())
}
fn log(&self, record: &Record<'_>) {
if !self.enabled(record.metadata()) {
return;
}
let config_opt: Option<&LoggerConfig> = CONFIG.get();
let format: LogFormat = config_opt.map_or(LogFormat::Plain, LoggerConfig::get_format);
let console: bool = config_opt.is_none_or(LoggerConfig::get_console);
let line: String = format_log_record(record, format);
if let Some(config) = config_opt
&& let Some(sink) = config.sink.as_ref()
{
sink.write_record(record.level().to_level_filter(), &line);
}
if let Some(Some(tx)) = WRITER_TX.get()
&& tx.try_send(WriterCommand::Line(line.clone())).is_err()
{
DROPPED_RECORDS.fetch_add(1, Ordering::Relaxed);
}
if console {
let mut out: io::StdoutLock<'static> = stdout().lock();
let _: io::Result<()> = out.write_all(line.as_bytes());
let _: io::Result<()> = out.write_all(b"\n");
}
}
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 {
pub fn sanitize_log_text(input: &str) -> String {
let mut out: String = String::with_capacity(input.len());
push_sanitized_plain(input, &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(())
}
pub fn get() -> Option<&'static LoggerConfig> {
CONFIG.get()
}
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 {
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 {
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(ATTRIBUTE_STARTED_AT);
let elapsed: u128 = match started_at {
Some(started_at) => started_at.elapsed().as_millis(),
None => 0,
};
let method: &RequestMethod = ctx.get_request().get_method();
let path: &str = ctx.get_request().get_path().as_str();
let status: usize = ctx.get_response().get_status_code();
let method_text: String = method.to_string();
log::info!(
"{} {} {} {}ms",
if method_text.is_empty() {
METHOD_UNKNOWN
} else {
method_text.as_str()
},
if path.is_empty() { PATH_UNKNOWN } else { path },
status,
elapsed
);
Status::Continue
}
}