kelora 2.0.0

A command-line log analysis tool with embedded Rhai scripting
Documentation
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
use crate::event::Event;
use crate::parsers::type_conversion::looks_like_json_number;
use crate::pipeline::EventParser;
use anyhow::Result;
use rhai::Dynamic;

pub struct LogfmtParser {
    auto_timestamp: bool,
}

impl LogfmtParser {
    pub fn new() -> Self {
        Self {
            auto_timestamp: true,
        }
    }

    pub fn new_without_auto_timestamp() -> Self {
        Self {
            auto_timestamp: false,
        }
    }

    /// Parse logfmt line: key1=value1 key2="value with spaces" key3=value3
    /// Adapted from Stelp but converted to work with Kelora's Dynamic system
    fn parse_logfmt_pairs(&self, line: &str) -> Result<Vec<(String, String)>, String> {
        let mut pairs = Vec::new();
        let mut chars = line.chars().peekable();

        while chars.peek().is_some() {
            // Skip whitespace
            while chars.peek() == Some(&' ') || chars.peek() == Some(&'\t') {
                chars.next();
            }

            if chars.peek().is_none() {
                break;
            }

            // Parse key
            let mut key = String::new();
            while let Some(&ch) = chars.peek() {
                if ch == '=' {
                    break;
                } else if ch == ' ' || ch == '\t' {
                    return Err("Key cannot contain spaces".to_string());
                } else {
                    key.push(chars.next().unwrap());
                }
            }

            if key.is_empty() {
                return Err("Empty key found".to_string());
            }

            // Expect '='
            if chars.next() != Some('=') {
                return Err(format!("Expected '=' after key '{}'", key));
            }

            // Parse value
            let mut value = String::new();
            if chars.peek() == Some(&'"') {
                // Quoted value
                chars.next(); // consume opening quote
                while let Some(ch) = chars.next() {
                    if ch == '"' {
                        // Check for escaped quote
                        if chars.peek() == Some(&'"') {
                            chars.next(); // consume escaped quote
                            value.push('"');
                        } else {
                            break; // end of quoted value
                        }
                    } else if ch == '\\' {
                        // Handle escape sequences
                        if let Some(escaped_ch) = chars.next() {
                            match escaped_ch {
                                'n' => value.push('\n'),
                                't' => value.push('\t'),
                                'r' => value.push('\r'),
                                '\\' => value.push('\\'),
                                '"' => value.push('"'),
                                _ => {
                                    value.push('\\');
                                    value.push(escaped_ch);
                                }
                            }
                        }
                    } else {
                        value.push(ch);
                    }
                }
            } else {
                // Unquoted value - read until space or end
                while let Some(&ch) = chars.peek() {
                    if ch == ' ' || ch == '\t' {
                        break;
                    } else {
                        value.push(chars.next().unwrap());
                    }
                }
            }

            pairs.push((key, value));
        }

        Ok(pairs)
    }

    /// Try to convert string to a numeric Dynamic value, falling back to string
    fn parse_value_to_dynamic(&self, value: String) -> Dynamic {
        // Only coerce values that are syntactically valid JSON numbers. This
        // keeps zero-padded IDs ("007"), signed values ("+1555..."), and
        // inf/nan as strings rather than silently rewriting them.
        if looks_like_json_number(&value) {
            // Try integer first
            if let Ok(i) = value.parse::<i64>() {
                return Dynamic::from(i);
            }

            // Try float (e.g. fractional, exponent, or integers beyond i64)
            if let Ok(f) = value.parse::<f64>() {
                return Dynamic::from(f);
            }
        }

        // Try boolean
        match value.to_lowercase().as_str() {
            "true" => return Dynamic::from(true),
            "false" => return Dynamic::from(false),
            _ => {}
        }

        // Default to string
        Dynamic::from(value)
    }
}

impl EventParser for LogfmtParser {
    fn parse(&self, line: &str) -> Result<Event> {
        let line = line.trim_end_matches('\n').trim_end_matches('\r');
        let pairs = self
            .parse_logfmt_pairs(line.trim())
            .map_err(|e| anyhow::anyhow!("{}", e))?;

        // Pre-allocate Event with capacity based on number of pairs
        let mut event = Event::with_capacity(line.to_string(), pairs.len());

        for (key, value) in pairs {
            // Convert string values to appropriate Dynamic types
            let dynamic_value = self.parse_value_to_dynamic(value);
            event.set_field(key, dynamic_value);
        }

        // Extract timestamp from the parsed data
        if self.auto_timestamp {
            event.extract_timestamp();
        }
        Ok(event)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::pipeline::EventParser;

    #[test]
    fn test_logfmt_parser_basic() {
        let parser = LogfmtParser::new();
        let result =
            EventParser::parse(&parser, r#"level=info message="test message" count=42"#).unwrap();

        assert_eq!(
            result
                .fields
                .get("level")
                .unwrap()
                .clone()
                .into_string()
                .unwrap(),
            "info"
        );
        assert_eq!(
            result
                .fields
                .get("message")
                .unwrap()
                .clone()
                .into_string()
                .unwrap(),
            "test message"
        );
        assert!(result.fields.get("count").is_some());
        assert_eq!(result.fields.get("count").unwrap().as_int().unwrap(), 42);
    }

    #[test]
    fn test_logfmt_parser_types() {
        let parser = LogfmtParser::new();
        let result = EventParser::parse(
            &parser,
            r#"str="hello" int=123 float=2.5 bool_true=true bool_false=false"#,
        )
        .unwrap();

        assert_eq!(
            result
                .fields
                .get("str")
                .unwrap()
                .clone()
                .into_string()
                .unwrap(),
            "hello"
        );
        assert_eq!(result.fields.get("int").unwrap().as_int().unwrap(), 123);
        assert_eq!(result.fields.get("float").unwrap().as_float().unwrap(), 2.5);
        assert!(result.fields.get("bool_true").unwrap().as_bool().unwrap());
        assert!(!result.fields.get("bool_false").unwrap().as_bool().unwrap());
    }

    #[test]
    fn test_logfmt_parser_quoted_values() {
        let parser = LogfmtParser::new();
        let result = EventParser::parse(
            &parser,
            r#"key1="value with spaces" key2="value with \"quotes\"" key3=simple"#,
        )
        .unwrap();

        assert_eq!(
            result
                .fields
                .get("key1")
                .unwrap()
                .clone()
                .into_string()
                .unwrap(),
            "value with spaces"
        );
        assert_eq!(
            result
                .fields
                .get("key2")
                .unwrap()
                .clone()
                .into_string()
                .unwrap(),
            "value with \"quotes\""
        );
        assert_eq!(
            result
                .fields
                .get("key3")
                .unwrap()
                .clone()
                .into_string()
                .unwrap(),
            "simple"
        );
    }

    #[test]
    fn test_logfmt_parser_escape_sequences() {
        let parser = LogfmtParser::new();
        let result = EventParser::parse(
            &parser,
            r#"newline="line1\nline2" tab="col1\tcol2" backslash="back\\slash""#,
        )
        .unwrap();

        assert_eq!(
            result
                .fields
                .get("newline")
                .unwrap()
                .clone()
                .into_string()
                .unwrap(),
            "line1\nline2"
        );
        assert_eq!(
            result
                .fields
                .get("tab")
                .unwrap()
                .clone()
                .into_string()
                .unwrap(),
            "col1\tcol2"
        );
        assert_eq!(
            result
                .fields
                .get("backslash")
                .unwrap()
                .clone()
                .into_string()
                .unwrap(),
            "back\\slash"
        );
    }

    #[test]
    fn test_logfmt_parser_empty_values() {
        let parser = LogfmtParser::new();
        let result =
            EventParser::parse(&parser, r#"empty="" quoted_empty="" unquoted_value=value"#)
                .unwrap();

        assert_eq!(
            result
                .fields
                .get("empty")
                .unwrap()
                .clone()
                .into_string()
                .unwrap(),
            ""
        );
        assert_eq!(
            result
                .fields
                .get("quoted_empty")
                .unwrap()
                .clone()
                .into_string()
                .unwrap(),
            ""
        );
        assert_eq!(
            result
                .fields
                .get("unquoted_value")
                .unwrap()
                .clone()
                .into_string()
                .unwrap(),
            "value"
        );
    }

    #[test]
    fn test_logfmt_parser_core_fields() {
        let parser = LogfmtParser::new();
        let result = EventParser::parse(
            &parser,
            r#"timestamp=2023-01-01T12:00:00Z level=error message="Connection failed" user=alice"#,
        )
        .unwrap();

        // Core fields should be accessible through fields map
        assert_eq!(
            result
                .fields
                .get("level")
                .unwrap()
                .clone()
                .into_string()
                .unwrap(),
            "error"
        );
        assert_eq!(
            result
                .fields
                .get("message")
                .unwrap()
                .clone()
                .into_string()
                .unwrap(),
            "Connection failed"
        );
        assert!(result.parsed_ts.is_some());

        // Other fields should be available
        assert_eq!(
            result
                .fields
                .get("user")
                .unwrap()
                .clone()
                .into_string()
                .unwrap(),
            "alice"
        );
    }

    #[test]
    fn test_logfmt_parser_errors() {
        let parser = LogfmtParser::new();

        // Missing equals sign
        assert!(EventParser::parse(&parser, "key value").is_err());

        // Empty key
        assert!(EventParser::parse(&parser, "=value").is_err());

        // Key with spaces
        assert!(EventParser::parse(&parser, "key with spaces=value").is_err());
    }
}