1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
#![warn(missing_docs)]
extern crate slog;
extern crate syslog;
extern crate nix;
use slog::{Drain, Level, Record, OwnedKVList};
use std::{io, fmt};
use std::sync::Mutex;
use std::cell::RefCell;
use slog::KV;
pub use syslog::Facility;
thread_local! {
static TL_BUF: RefCell<Vec<u8>> = RefCell::new(Vec::with_capacity(128))
}
fn level_to_severity(level: slog::Level) -> syslog::Severity {
match level {
Level::Critical => syslog::Severity::LOG_CRIT,
Level::Error => syslog::Severity::LOG_ERR,
Level::Warning => syslog::Severity::LOG_WARNING,
Level::Info => syslog::Severity::LOG_NOTICE,
Level::Debug => syslog::Severity::LOG_INFO,
Level::Trace => syslog::Severity::LOG_DEBUG,
}
}
pub struct Streamer3164 {
io: Mutex<Box<syslog::Logger>>,
format: Format3164,
}
impl Streamer3164 {
pub fn new(logger: Box<syslog::Logger>) -> Self {
Streamer3164 {
io: Mutex::new(logger),
format: Format3164::new(),
}
}
}
impl Drain for Streamer3164 {
type Err = io::Error;
type Ok = ();
fn log(&self, info: &Record, logger_values: &OwnedKVList) -> io::Result<()> {
TL_BUF.with(|buf| {
let mut buf = buf.borrow_mut();
let res = {
|| {
try!(self.format.format(&mut *buf, info, logger_values));
let sever = level_to_severity(info.level());
{
let io = try!(self.io
.lock()
.map_err(|_| io::Error::new(io::ErrorKind::Other, "locking error")));
let buf = String::from_utf8_lossy(&buf);
let buf = io.format_3164(sever, &buf).into_bytes();
let mut pos = 0;
while pos < buf.len() {
let n = try!(io.send_raw(&buf[pos..]));
if n == 0 {
break
}
pos += n;
}
}
Ok(())
}
}();
buf.clear();
res
})
}
}
pub struct Format3164;
impl Format3164 {
pub fn new() -> Self {
Format3164
}
fn format(&self,
io: &mut io::Write,
record: &Record,
logger_kv: &OwnedKVList)
-> io::Result<()> {
try!(write!(io, "{}", record.msg()));
let mut ser = KSV::new(io);
{
try!(logger_kv.serialize(record, &mut ser));
try!(record.kv().serialize(record, &mut ser));
}
Ok(())
}
}
struct KSV<W: io::Write> {
io: W,
}
impl<W: io::Write> KSV<W> {
fn new(io: W) -> Self {
KSV {
io: io,
}
}
}
impl<W: io::Write> slog::Serializer for KSV<W> {
fn emit_arguments(&mut self, key: &str, val: &fmt::Arguments) -> slog::Result {
try!(write!(self.io, ", {}: {}", key, val));
Ok(())
}
}
pub fn unix_3164(facility: syslog::Facility) -> io::Result<Streamer3164> {
syslog::unix(facility).map(Streamer3164::new)
}