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
use rusoto_logs::OutputLogEvent;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::convert::{TryFrom, TryInto};
use anyhow::{Error, Result};
use chrono::NaiveDateTime;
mod dotnet;
mod node;
mod python;
#[derive(Default, Debug, Deserialize, Clone)]
pub struct RawCloudWatchLog {
pub time: String,
pub r#type: String,
pub record: serde_json::Value,
}
impl TryFrom<OutputLogEvent> for RawCloudWatchLog {
type Error = anyhow::Error;
fn try_from(log: OutputLogEvent) -> Result<Self> {
match log {
OutputLogEvent { message: Some(record), timestamp: Some(time), ingestion_time: _ } =>
Ok (RawCloudWatchLog {
record: serde_json::Value::String(record),
r#type: "function".to_string(),
time: NaiveDateTime::from_timestamp(0, time.try_into().unwrap()).format("%Y-%m-%dT%H:%M:%SZ").to_string()
}),
_ => Err(Error::msg(format!("Unable to parse {:?} as RawCloudWatchLog", log))),
}
}
}
#[derive(Debug, Serialize, Clone)]
pub struct StructuredLog {
pub timestamp: Option<String>,
pub guid: Option<String>,
pub level: Option<LogLevel>,
pub data: Value,
}
impl TryFrom<String> for LogLevel {
type Error = anyhow::Error;
fn try_from(level: String) -> Result<Self> {
match level.as_str() {
"INFO" => Ok(LogLevel::Info),
"WARN" => Ok(LogLevel::Warn),
"ERROR" => Ok(LogLevel::Error),
_ => Err(Error::msg(format!("Unable to parse {} as LogLevel", level))),
}
}
}
#[derive(Debug, Clone)]
pub enum Log {
Unformatted(StructuredLog),
Formatted(serde_json::Value),
}
impl ToString for Log {
fn to_string(&self) -> String {
match self {
Log::Unformatted(data) => serde_json::to_string(data).unwrap(),
Log::Formatted(data) => data.to_string(),
}
}
}
#[derive(Debug, Serialize, PartialEq, Clone)]
pub enum LogLevel {
#[serde(rename(serialize = "INFO"))]
Info,
#[serde(rename(serialize = "WARN"))]
Warn,
#[serde(rename(serialize = "ERROR"))]
Error,
}
pub fn parse_log(log: RawCloudWatchLog) -> Result<Log> {
match log.record {
Value::String(_) => try_parse_cloudwatch_log(&log),
_ => Err(Error::msg(format!("Expected String {}", log.record))),
}
}
pub fn parse_logs(logs: Vec<RawCloudWatchLog>) -> Vec<Log> {
logs.into_iter()
.filter(|log| match log.r#type.as_str() {
"function" => true,
_ => {
println!("{:?}", log);
false
}
})
.map(parse_log)
.flatten()
.collect()
}
fn try_parse_cloudwatch_log(log: &RawCloudWatchLog) -> Result<Log> {
match node::parse(log) {
Some(dto) => {
return Ok(dto);
}
_ => (),
};
match python::parse(log) {
Some(dto) => {
return Ok(dto);
}
_ => (),
};
match dotnet::parse(log) {
Some(dto) => {
return Ok(dto);
}
_ => (),
};
Err(Error::msg(format!("Unable to parse {:?}", log)))
}
#[cfg(test)]
mod tests {
use super::try_parse_cloudwatch_log;
use crate::{LogLevel, RawCloudWatchLog, Log};
#[test]
fn can_parse_node() {
let input =
RawCloudWatchLog {
record:
serde_json::Value::String("2020-11-18T23:52:30.128Z\t6e48723a-1596-4313-a9af-e4da9214d637\tINFO\tHello World\n".to_string())
, ..Default::default()
};
let output = try_parse_cloudwatch_log(&input);
assert_eq!(output.is_ok(), true);
match output.unwrap() {
Log::Unformatted(log) => {
assert_eq!(log.timestamp.unwrap(), "2020-11-18T23:52:30.128Z");
assert_eq!(log.guid.unwrap(), "6e48723a-1596-4313-a9af-e4da9214d637");
assert_eq!(log.level.unwrap(), LogLevel::Info);
assert_eq!(log.data, "Hello World\n");
},
_ => {
panic!("Expected Cloudwatch formatted log");
}
}
}
#[test]
fn can_parse_python() {
let input = RawCloudWatchLog {
record: serde_json::Value::String(
"[INFO] 2020-11-18T23:52:30.128Z 6e48723a-1596-4313-a9af-e4da9214d637 Hello World\n"
.to_string(),
),
..Default::default()
};
let output = try_parse_cloudwatch_log(&input);
assert_eq!(output.is_ok(), true);
match output.unwrap() {
Log::Unformatted(log) => {
assert_eq!(log.timestamp.unwrap(), "2020-11-18T23:52:30.128Z");
assert_eq!(log.guid.unwrap(), "6e48723a-1596-4313-a9af-e4da9214d637");
assert_eq!(log.level.unwrap(), LogLevel::Info);
assert_eq!(log.data, "Hello World\n");
},
_ => {
panic!("Expected Cloudwatch formatted log");
}
}
}
#[test]
fn can_parse_dotnet() {
let input = RawCloudWatchLog {
record: serde_json::Value::String(
"{ \"statusCode\": 200, \"body\": \"DotNet\" }".to_string(),
),
time: "2020-11-18T23:52:30.128Z".to_string(),
..Default::default()
};
let output = try_parse_cloudwatch_log(&input);
assert_eq!(output.is_ok(), true);
match output.unwrap() {
Log::Formatted(log) => {
assert_eq!(log["body"], "DotNet");
assert_eq!(log["statusCode"], 200);
}
_ => {
panic!("Expected Preformatted log");
}
}
}
#[test]
fn cannot_parse() {
let input = RawCloudWatchLog { record: serde_json::Value::String("Bad log".to_string()), ..Default::default()};
let output = try_parse_cloudwatch_log(&input);
assert_eq!(output.is_err(), true);
}
}