cmtraceopen_parser/parser/
severity.rs1use crate::models::log_entry::Severity;
2
3#[inline]
6fn contains_ci(haystack: &str, needle: &[u8]) -> bool {
7 let h = haystack.as_bytes();
8 let n_len = needle.len();
9 if h.len() < n_len {
10 return false;
11 }
12 for window in h.windows(n_len) {
13 if window
14 .iter()
15 .zip(needle.iter())
16 .all(|(a, b)| a.to_ascii_lowercase() == *b)
17 {
18 return true;
19 }
20 }
21 false
22}
23
24pub fn detect_severity_from_text(text: &str) -> Severity {
28 if contains_ci(text, b"error")
30 || contains_ci(text, b"exception")
31 || contains_ci(text, b"critical")
32 || contains_ci(text, b"fatal")
33 {
34 return Severity::Error;
35 }
36
37 if contains_ci(text, b"fail") && !contains_ci(text, b"failover") {
39 return Severity::Error;
40 }
41
42 if contains_ci(text, b"warn") {
44 return Severity::Warning;
45 }
46
47 Severity::Info
48}
49
50#[cfg(test)]
51mod tests {
52 use super::*;
53
54 #[test]
55 fn test_error_keyword() {
56 assert_eq!(
57 detect_severity_from_text("An error occurred"),
58 Severity::Error
59 );
60 }
61
62 #[test]
63 fn test_exception_keyword() {
64 assert_eq!(
65 detect_severity_from_text("NullPointerException thrown"),
66 Severity::Error
67 );
68 }
69
70 #[test]
71 fn test_critical_keyword() {
72 assert_eq!(
73 detect_severity_from_text("CRITICAL: disk full"),
74 Severity::Error
75 );
76 }
77
78 #[test]
79 fn test_fatal_keyword() {
80 assert_eq!(
81 detect_severity_from_text("Fatal: cannot continue"),
82 Severity::Error
83 );
84 }
85
86 #[test]
87 fn test_fail_keyword() {
88 assert_eq!(
89 detect_severity_from_text("Operation failed"),
90 Severity::Error
91 );
92 }
93
94 #[test]
95 fn test_failover_excluded() {
96 assert_eq!(
97 detect_severity_from_text("Failover to secondary node"),
98 Severity::Info
99 );
100 }
101
102 #[test]
103 fn test_warning_keyword() {
104 assert_eq!(
105 detect_severity_from_text("Warning: low memory"),
106 Severity::Warning
107 );
108 }
109
110 #[test]
111 fn test_warn_keyword() {
112 assert_eq!(
113 detect_severity_from_text("[WARN] config missing"),
114 Severity::Warning
115 );
116 }
117
118 #[test]
119 fn test_info_default() {
120 assert_eq!(
121 detect_severity_from_text("Service started successfully"),
122 Severity::Info
123 );
124 }
125
126 #[test]
127 fn test_case_insensitive() {
128 assert_eq!(
129 detect_severity_from_text("ERROR: something broke"),
130 Severity::Error
131 );
132 assert_eq!(
133 detect_severity_from_text("WARNING: check this"),
134 Severity::Warning
135 );
136 }
137}