Skip to content

Commit 1fdf08e

Browse files
committed
feature: Custom format function
1 parent 84a4307 commit 1fdf08e

File tree

1 file changed

+20
-4
lines changed

1 file changed

+20
-4
lines changed

src/lib.rs

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,9 @@ use std::fmt;
7171
use std::ptr;
7272

7373
pub use env_logger::filter::{Filter, Builder as FilterBuilder};
74+
pub use env_logger::fmt::Formatter;
75+
76+
pub(crate) type FormatFn = Box<dyn Fn(&mut dyn fmt::Write, &Record) -> fmt::Result + Sync + Send>;
7477

7578
/// Output log to android system.
7679
#[cfg(target_os = "android")]
@@ -153,10 +156,13 @@ impl Log for AndroidLogger {
153156

154157
// If a custom tag is used, add the module path to the message.
155158
// Use PlatformLogWriter to output chunks if they exceed max size.
156-
let _ = if custom_tag.is_some() {
157-
fmt::write(&mut writer, format_args!("{}: {}", module_path, *record.args()))
158-
} else {
159-
fmt::write(&mut writer, *record.args())
159+
let _ = match (custom_tag, &config.custom_format) {
160+
(_, Some(format)) => format(&mut writer, record),
161+
(Some(_), _) => fmt::write(
162+
&mut writer,
163+
format_args!("{}: {}", module_path, *record.args()),
164+
),
165+
_ => fmt::write(&mut writer, *record.args()),
160166
};
161167

162168
// output the remaining message (this would usually be the most common case)
@@ -192,6 +198,7 @@ pub struct Config {
192198
log_level: Option<Level>,
193199
filter: Option<env_logger::filter::Filter>,
194200
tag: Option<CString>,
201+
custom_format: Option<FormatFn>,
195202
}
196203

197204
impl Default for Config {
@@ -200,6 +207,7 @@ impl Default for Config {
200207
log_level: None,
201208
filter: None,
202209
tag: None,
210+
custom_format: None,
203211
}
204212
}
205213
}
@@ -231,6 +239,14 @@ impl Config {
231239
self.tag = Some(CString::new(tag).expect("Can't convert tag to CString"));
232240
self
233241
}
242+
243+
pub fn format<F>(mut self, format: F) -> Self
244+
where
245+
F: Fn(&mut dyn fmt::Write, &Record) -> fmt::Result + Sync + Send + 'static,
246+
{
247+
self.custom_format = Some(Box::new(format));
248+
self
249+
}
234250
}
235251

236252
struct PlatformLogWriter<'a> {

0 commit comments

Comments
 (0)