Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changes/allow-log-formatter-per-target.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"log": "minor"
"log-js": "minor"
---

Allow specifying a log formatter per target using the `format` method on `Target`.
23 changes: 23 additions & 0 deletions plugins/log/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -182,10 +182,13 @@ pub enum TargetKind {
Dispatch(fern::Dispatch),
}

type Formatter = dyn Fn(FormatCallback, &Arguments, &Record) + Send + Sync + 'static;

/// A log target.
pub struct Target {
kind: TargetKind,
filters: Vec<Box<Filter>>,
formatter: Option<Box<Formatter>>,
}

impl Target {
Expand All @@ -194,6 +197,7 @@ impl Target {
Self {
kind,
filters: Vec::new(),
formatter: None,
}
}

Expand All @@ -205,6 +209,15 @@ impl Target {
self.filters.push(Box::new(filter));
self
}

#[inline]
pub fn format<F>(mut self, formatter: F) -> Self
where
F: Fn(FormatCallback, &Arguments, &Record) + Send + Sync + 'static,
{
self.formatter.replace(Box::new(formatter));
self
}
}

pub struct Builder {
Expand Down Expand Up @@ -276,6 +289,13 @@ impl Builder {
self
}

pub fn clear_format(mut self) -> Self {
self.dispatch = self.dispatch.format(|out, message, _record| {
out.finish(format_args!("{message}"));
});
self
}

pub fn format<F>(mut self, formatter: F) -> Self
where
F: Fn(FormatCallback, &Arguments, &Record) + Sync + Send + 'static,
Expand Down Expand Up @@ -384,6 +404,9 @@ impl Builder {
for filter in target.filters {
target_dispatch = target_dispatch.filter(filter);
}
if let Some(formatter) = target.formatter {
target_dispatch = target_dispatch.format(formatter);
}

let logger = match target.kind {
#[cfg(target_os = "android")]
Expand Down
Loading