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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
use std::{
collections::BTreeMap,
env,
fmt::{self, Display, Formatter},
process,
};
use chrono::{DateTime, SecondsFormat, Utc};
use log::kv::{self, Key, Value, Visitor};
use once_cell::sync::Lazy;
use serde::{Serialize, Serializer};
use casper_types::SemVer;
use crate::shared::{
logging::{DEFAULT_MESSAGE_TEMPLATE, MESSAGE_TEMPLATE_KEY},
utils,
};
static PROCESS_ID: Lazy<u32> = Lazy::new(process::id);
static PROCESS_NAME: Lazy<String> = Lazy::new(|| {
env::current_exe()
.ok()
.and_then(|full_path| {
full_path
.file_stem()
.map(|file_stem| file_stem.to_string_lossy().to_string())
})
.unwrap_or_else(|| "unknown-process".to_string())
});
static HOST_NAME: Lazy<String> = Lazy::new(|| {
hostname::get()
.map(|host_name| host_name.to_string_lossy().to_string())
.unwrap_or_else(|_| "unknown-host".to_string())
});
static MESSAGE_TYPE: Lazy<String> = Lazy::new(|| "ee-structured".to_string());
static MESSAGE_TYPE_VERSION: Lazy<MessageTypeVersion> = Lazy::new(MessageTypeVersion::default);
#[derive(Clone, Debug, Serialize)]
pub(crate) struct StructuredMessage {
timestamp: TimestampRfc3999,
process_id: u32,
process_name: String,
host_name: String,
log_level: String,
priority: Priority,
message_type: String,
message_type_version: MessageTypeVersion,
message_id: MessageId,
description: String,
properties: MessageProperties,
}
impl StructuredMessage {
pub fn new(log_level: String, message_id: MessageId, properties: MessageProperties) -> Self {
let timestamp = TimestampRfc3999::default();
let process_id = *PROCESS_ID;
let process_name = PROCESS_NAME.clone();
let host_name = HOST_NAME.clone();
let priority = Priority::from(log_level.as_str());
let message_type = MESSAGE_TYPE.clone();
let message_type_version = *MESSAGE_TYPE_VERSION;
let description = properties.get_formatted_message();
StructuredMessage {
timestamp,
process_id,
process_name,
host_name,
log_level,
priority,
message_type,
message_type_version,
message_id,
description,
properties,
}
}
}
impl Display for StructuredMessage {
fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
let json = utils::jsonify(self, false);
write!(
formatter,
"{timestamp} {loglevel} {priority} {hostname} {facility} payload={payload}",
timestamp = self.timestamp,
loglevel = self.log_level.to_string().to_uppercase(),
priority = self.priority,
hostname = self.host_name,
facility = self.process_name,
payload = json
)
}
}
#[derive(Clone, Copy, Debug, Hash, Serialize)]
struct Priority(u8);
impl From<&str> for Priority {
fn from(level: &str) -> Self {
match level {
"Error" => Priority(3),
"Warn" => Priority(4),
"Info" => Priority(5),
"Debug" => Priority(6),
"Metric" => Priority(6),
"Trace" => Priority(7),
_ => Priority(255),
}
}
}
impl Display for Priority {
fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
self.0.fmt(formatter)
}
}
#[derive(Debug, Copy, Clone)]
struct MessageTypeVersion(SemVer);
impl Display for MessageTypeVersion {
fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
self.0.fmt(formatter)
}
}
impl Default for MessageTypeVersion {
fn default() -> Self {
MessageTypeVersion(SemVer::V1_0_0)
}
}
impl Serialize for MessageTypeVersion {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let s = format!("{}.{}.{}", self.0.major, self.0.minor, self.0.patch);
serializer.serialize_str(&s)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
pub(crate) struct MessageId(usize);
impl MessageId {
pub fn new(id: usize) -> MessageId {
MessageId(id)
}
}
#[derive(Clone, Debug, Hash, Serialize)]
pub(crate) struct TimestampRfc3999(String);
impl Default for TimestampRfc3999 {
fn default() -> Self {
let now: DateTime<Utc> = Utc::now();
TimestampRfc3999(now.to_rfc3339_opts(SecondsFormat::Millis, true))
}
}
impl Display for TimestampRfc3999 {
fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
self.0.fmt(formatter)
}
}
#[derive(Clone, Debug, Hash, Serialize)]
pub(crate) struct MessageProperties(BTreeMap<String, String>);
impl MessageProperties {
pub fn new(mut properties: BTreeMap<String, String>) -> MessageProperties {
properties
.entry(MESSAGE_TEMPLATE_KEY.to_string())
.or_insert_with(|| DEFAULT_MESSAGE_TEMPLATE.to_string());
MessageProperties(properties)
}
pub fn insert(&mut self, key: String, value: String) -> Option<String> {
self.0.insert(key, value)
}
pub fn get_formatted_message(&self) -> String {
let message_template = match self.0.get(MESSAGE_TEMPLATE_KEY) {
Some(message_template) if !message_template.is_empty() => message_template,
_ => return String::new(),
};
let mut buf = String::new();
let mut candidate_key = String::new();
let mut key_seek = false;
let properties = &self.0;
for c in message_template.chars() {
match c {
'{' => {
key_seek = true;
candidate_key.clear();
}
'}' if key_seek => {
key_seek = false;
if let Some(v) = properties.get(&candidate_key) {
buf.push_str(v);
}
}
'}' => (),
c if key_seek => candidate_key.push(c),
c => buf.push(c),
}
}
buf
}
}
impl Default for MessageProperties {
fn default() -> Self {
MessageProperties::new(BTreeMap::new())
}
}
impl<'kvs> Visitor<'kvs> for MessageProperties {
fn visit_pair(&mut self, key: Key<'kvs>, value: Value<'kvs>) -> Result<(), kv::Error> {
let value = value
.to_string()
.trim_matches('"')
.replace(r#"\'"#, r#"'"#)
.replace(r#"\""#, r#"""#)
.replace(r#"\\"#, r#"\"#);
self.0.insert(key.to_string(), value);
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::shared::logging::DEFAULT_MESSAGE_KEY;
#[test]
fn should_get_process_id() {
assert!(
*PROCESS_ID != 0,
"PROCESS_ID should not be 0: {}",
*PROCESS_ID
);
}
#[test]
fn should_get_process_name() {
assert!(!PROCESS_NAME.is_empty(), "PROCESS_NAME should have chars")
}
#[test]
fn should_get_host_name() {
assert!(!HOST_NAME.is_empty(), "HOST_NAME should have chars")
}
#[test]
fn should_format_message_template_default_use_case() {
let mut properties: BTreeMap<String, String> = BTreeMap::new();
properties.insert(
DEFAULT_MESSAGE_KEY.to_string(),
"i am a log message".to_string(),
);
let props = MessageProperties::new(properties);
let formatted = props.get_formatted_message();
assert_eq!(
formatted,
"i am a log message".to_string(),
"message malformed"
)
}
#[test]
fn should_format_message_template_starting_and_ending_with_braces() {
let mut properties: BTreeMap<String, String> = BTreeMap::new();
properties.insert(
DEFAULT_MESSAGE_KEY.to_string(),
"i convey meaning".to_string(),
);
properties.insert("abc".to_string(), "some text".to_string());
properties.insert("some-hash".to_string(), "A@#$!@#".to_string());
properties.insert("byz".to_string(), "".to_string());
let template =
"{abc} i'm a message temp{byz}late some-hash:{some-hash} msg:{message}".to_string();
properties.insert(MESSAGE_TEMPLATE_KEY.to_string(), template);
let props = MessageProperties::new(properties);
let formatted = props.get_formatted_message();
assert_eq!(
formatted,
"some text i\'m a message template some-hash:A@#$!@# msg:i convey meaning".to_string(),
"message malformed"
)
}
#[test]
fn should_format_message_template_with_escaped_braces() {
let mut properties: BTreeMap<String, String> = BTreeMap::new();
properties.insert(DEFAULT_MESSAGE_KEY.to_string(), "a message".to_string());
properties.insert("more-data".to_string(), "some additional data".to_string());
let template = "this is {{message}} with {{{more-data}}}".to_string();
properties.insert(MESSAGE_TEMPLATE_KEY.to_string(), template);
let props = MessageProperties::new(properties);
let formatted = props.get_formatted_message();
assert_eq!(
formatted,
"this is a message with some additional data".to_string(),
"message malformed"
)
}
#[test]
fn should_format_message_template_with_no_properties() {
let properties: BTreeMap<String, String> = BTreeMap::new();
let props = MessageProperties::new(properties);
let formatted = props.get_formatted_message();
assert_eq!(formatted, "".to_string(), "message malformed")
}
#[test]
fn should_format_message_template_with_unclosed_brace() {
let mut properties: BTreeMap<String, String> = BTreeMap::new();
let template = "{message".to_string();
properties.insert(MESSAGE_TEMPLATE_KEY.to_string(), template);
let props = MessageProperties::new(properties);
let formatted = props.get_formatted_message();
assert_eq!(formatted, "".to_string(), "message malformed")
}
#[test]
fn should_format_message_template_with_unopened_brace() {
let mut properties: BTreeMap<String, String> = BTreeMap::new();
let template = "message}".to_string();
properties.insert(MESSAGE_TEMPLATE_KEY.to_string(), template);
let props = MessageProperties::new(properties);
let formatted = props.get_formatted_message();
assert_eq!(formatted, "message".to_string(), "message malformed")
}
#[test]
fn should_format_message_template_with_mismatched_braces_left() {
let mut properties: BTreeMap<String, String> = BTreeMap::new();
let template = "{{message}".to_string();
properties.insert(MESSAGE_TEMPLATE_KEY.to_string(), template);
let props = MessageProperties::new(properties);
let formatted = props.get_formatted_message();
assert_eq!(formatted, "".to_string(), "message malformed")
}
#[test]
fn should_format_message_template_with_mismatched_braces_right() {
let mut properties: BTreeMap<String, String> = BTreeMap::new();
let template = "{message}}".to_string();
properties.insert(MESSAGE_TEMPLATE_KEY.to_string(), template);
let props = MessageProperties::new(properties);
let formatted = props.get_formatted_message();
assert_eq!(formatted, "".to_string(), "message malformed")
}
#[test]
fn should_validate_log_message() {
let test_msg = "test_message".to_string();
let mut properties = MessageProperties::default();
properties.insert(DEFAULT_MESSAGE_KEY.to_string(), test_msg);
let l = StructuredMessage::new("Error".to_string(), MessageId::new(1), properties);
assert!(
should_have_rfc3339_timestamp(&l),
"rfc3339 timestamp required"
);
assert!(should_have_log_level(&l), "log level required");
assert!(should_have_process_id(&l), "process id required");
assert!(should_have_process_name(&l), "process name required");
assert!(should_have_host_name(&l), "host name required");
assert!(should_have_at_least_one_property(&l), "properties required");
assert!(should_have_description(&l), "description required");
}
fn should_have_rfc3339_timestamp(l: &StructuredMessage) -> bool {
match DateTime::parse_from_rfc3339(&l.timestamp.0) {
Ok(_d) => true,
Err(_) => false,
}
}
fn should_have_log_level(l: &StructuredMessage) -> bool {
!l.log_level.is_empty()
}
fn should_have_description(l: &StructuredMessage) -> bool {
!l.description.is_empty()
}
fn should_have_process_id(l: &StructuredMessage) -> bool {
l.process_id > 0
}
fn should_have_process_name(l: &StructuredMessage) -> bool {
!l.process_name.is_empty()
}
fn should_have_host_name(l: &StructuredMessage) -> bool {
!l.host_name.is_empty()
}
fn should_have_at_least_one_property(l: &StructuredMessage) -> bool {
!l.properties.0.is_empty()
}
}