Skip to content

Commit 23ce65f

Browse files
committed
feat: Syslog-adapted formating and auto-detection
1 parent ced793e commit 23ce65f

File tree

2 files changed

+36
-2
lines changed

2 files changed

+36
-2
lines changed

src/fmt/mod.rs

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,6 @@ use std::io::prelude::Write;
6363
use std::rc::Rc;
6464
use std::{fmt, io, mem};
6565

66-
#[cfg(feature = "color")]
6766
use log::Level;
6867
use log::Record;
6968

@@ -218,6 +217,7 @@ pub(crate) type FormatFn = Box<dyn RecordFormat + Sync + Send>;
218217
#[derive(Default)]
219218
pub(crate) struct Builder {
220219
pub(crate) format: ConfigurableFormat,
220+
pub(crate) format_syslog: bool,
221221
built: bool,
222222
}
223223

@@ -238,7 +238,25 @@ impl Builder {
238238
},
239239
);
240240

241-
Box::new(built.format)
241+
if !built.format_syslog {
242+
Box::new(built.format)
243+
} else {
244+
Box::new(|buf: &mut Formatter, record: &Record<'_>| {
245+
writeln!(
246+
buf,
247+
"<{}>{}: {}",
248+
match record.level() {
249+
Level::Error => 3,
250+
Level::Warn => 4,
251+
Level::Info => 6,
252+
Level::Debug => 7,
253+
Level::Trace => 7,
254+
},
255+
record.target(),
256+
record.args()
257+
)
258+
})
259+
}
242260
}
243261
}
244262

src/logger.rs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,10 @@ impl Builder {
160160
self.parse_write_style(&s);
161161
}
162162

163+
if env.is_daemon() {
164+
self.format.format_syslog = true;
165+
}
166+
163167
self
164168
}
165169

@@ -299,6 +303,13 @@ impl Builder {
299303
self
300304
}
301305

306+
/// If set to true, format log messages in a Syslog-adapted format.
307+
/// Overrides the auto-detected value.
308+
pub fn format_syslog(&mut self, syslog: bool) -> &mut Self {
309+
self.format.format_syslog = syslog;
310+
self
311+
}
312+
302313
/// Set the format for structured key/value pairs in the log record
303314
///
304315
/// With the default format, this function is called for each record and should format
@@ -820,6 +831,11 @@ impl<'a> Env<'a> {
820831
fn get_write_style(&self) -> Option<String> {
821832
self.write_style.get()
822833
}
834+
835+
fn is_daemon(&self) -> bool {
836+
//TODO: support more logging systems
837+
Var::new("JOURNAL_STREAM").get().is_some()
838+
}
823839
}
824840

825841
impl<'a, T> From<T> for Env<'a>

0 commit comments

Comments
 (0)