Skip to content

Commit 2a625ad

Browse files
feat(log): Allow a log formatter per target (#3065)
Co-authored-by: Fabian-Lars <[email protected]>
1 parent 371cd82 commit 2a625ad

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
"log": "minor"
3+
"log-js": "minor"
4+
---
5+
6+
Allow specifying a log formatter per target using the `format` method on `Target`.

plugins/log/src/lib.rs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,10 +182,13 @@ pub enum TargetKind {
182182
Dispatch(fern::Dispatch),
183183
}
184184

185+
type Formatter = dyn Fn(FormatCallback, &Arguments, &Record) + Send + Sync + 'static;
186+
185187
/// A log target.
186188
pub struct Target {
187189
kind: TargetKind,
188190
filters: Vec<Box<Filter>>,
191+
formatter: Option<Box<Formatter>>,
189192
}
190193

191194
impl Target {
@@ -194,6 +197,7 @@ impl Target {
194197
Self {
195198
kind,
196199
filters: Vec::new(),
200+
formatter: None,
197201
}
198202
}
199203

@@ -205,6 +209,15 @@ impl Target {
205209
self.filters.push(Box::new(filter));
206210
self
207211
}
212+
213+
#[inline]
214+
pub fn format<F>(mut self, formatter: F) -> Self
215+
where
216+
F: Fn(FormatCallback, &Arguments, &Record) + Send + Sync + 'static,
217+
{
218+
self.formatter.replace(Box::new(formatter));
219+
self
220+
}
208221
}
209222

210223
pub struct Builder {
@@ -276,6 +289,13 @@ impl Builder {
276289
self
277290
}
278291

292+
pub fn clear_format(mut self) -> Self {
293+
self.dispatch = self.dispatch.format(|out, message, _record| {
294+
out.finish(format_args!("{message}"));
295+
});
296+
self
297+
}
298+
279299
pub fn format<F>(mut self, formatter: F) -> Self
280300
where
281301
F: Fn(FormatCallback, &Arguments, &Record) + Sync + Send + 'static,
@@ -384,6 +404,9 @@ impl Builder {
384404
for filter in target.filters {
385405
target_dispatch = target_dispatch.filter(filter);
386406
}
407+
if let Some(formatter) = target.formatter {
408+
target_dispatch = target_dispatch.format(formatter);
409+
}
387410

388411
let logger = match target.kind {
389412
#[cfg(target_os = "android")]

0 commit comments

Comments
 (0)