Created
September 23, 2015 09:41
-
-
Save Leechael/766e64fe148a06ddb306 to your computer and use it in GitHub Desktop.
Simple log parser in Rust-Lang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::fs::File; | |
use std::io::BufRead; | |
use std::io::BufReader; | |
use std::path::Path; | |
struct Hit { | |
ip: String, | |
datetime: String, | |
method: String, | |
path: String, | |
http_version: f32, | |
status: u16, | |
size: u32, | |
referer: String, | |
user_agent: String | |
} | |
fn parse_oneline(s : &str, l : usize) -> Hit { | |
let ptr_ip; | |
let ptr_datetime; | |
let ptr_method; | |
let ptr_path; | |
let ptr_http_version; | |
let ptr_status; | |
let ptr_size; | |
let ptr_referer; | |
let ptr_ua; | |
let mut x : usize = 0; | |
let mut y : usize = s.find(" ").unwrap(); | |
ptr_ip = &s[ x .. y ]; | |
x = s.find("[").unwrap() + 1; | |
y = x + 26; | |
ptr_datetime = &s[ x .. y ]; | |
x = y + s[ y .. l ].find('"').unwrap() + 1; | |
y = x + s[ x .. l ].find(' ').unwrap(); | |
ptr_method = &s[ x .. y ]; | |
x = y + 1; | |
y = x + s[ x .. l ].find(' ').unwrap() - 1; | |
ptr_path = &s[ x .. y ]; | |
x = y + 7; | |
y = x + s[ x .. l ].find('"').unwrap(); | |
ptr_http_version = &s[ x .. y ]; | |
x = y + 2; | |
y = x + 3; | |
ptr_status = &s[ x .. y ]; | |
x = y + 1; | |
y = x + s[ x .. l ].find(' ').unwrap(); | |
ptr_size = &s[ x .. y ]; | |
x = y + 2; | |
y = x + s[ x .. l ].find('"').unwrap(); | |
ptr_referer = &s[ x .. y ]; | |
ptr_ua = &s[ y+3 .. l-1 ]; | |
let _hit = Hit{ | |
ip: ptr_ip.to_string(), | |
datetime: ptr_datetime.to_string(), | |
method: ptr_method.to_string(), | |
path: ptr_path.to_string(), | |
http_version: ptr_http_version.parse::<f32>().unwrap(), | |
status: ptr_status.parse::<u16>().unwrap(), | |
size: ptr_size.parse::<u32>().unwrap(), | |
referer: ptr_referer.to_string(), | |
user_agent: ptr_ua.to_string() | |
}; | |
return _hit; | |
} | |
fn main() { | |
let file = match File::open("nginx.log") { | |
Ok(file) => file, | |
Err(..) => panic!("ohh"), | |
}; | |
let mut reader = BufReader::new(&file); | |
let mut vec = Vec::new(); | |
for line in reader.lines() { | |
if (line.is_ok()) { | |
let s = line.unwrap(); | |
vec.push(parse_oneline(&s as &str, s.len())); | |
} | |
} | |
println!("Total {} records.", vec.len()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment