Created
October 2, 2015 22:29
-
-
Save jirojo2/86a0f82ccb304bd2396e to your computer and use it in GitHub Desktop.
Some experiment for casual log parsing for @SuperBuker
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
#include <iostream> | |
#include <fstream> | |
#include <sstream> | |
#include <string> | |
#include <vector> | |
#include <regex> | |
#include <time.h> | |
using namespace std; | |
struct LogEntry | |
{ | |
string verb; | |
string path; | |
int code; | |
int responseSize; | |
int timestamp; | |
}; | |
int main() | |
{ | |
cout << "Parsing log file..." << endl; | |
// [23/Jul/2015:06:25:27 +0200] "GET / HTTP/1.1" 200 8939 | |
const regex r("\\[([^\\]]+)\\] \\\"([\\S]+) ([\\S]+) HTTP/1.1\\\" ([\\d]+) ([\\d]+)"); | |
const string dateFormat("%d/%b/%Y:%H:%M:%S %z"); | |
// Open file stream | |
ifstream logfile("test4.log"); | |
vector<LogEntry> logEntries; | |
smatch match; | |
string line; | |
while (getline(logfile, line)) | |
{ | |
try | |
{ | |
if (!regex_search(line, match, r)) | |
continue; | |
} | |
catch (regex_error& e) | |
{ | |
cerr << "PARSING ERROR: " << e.code() << endl; | |
} | |
string date; | |
LogEntry entry; | |
date = match[1]; | |
entry.verb = match[2]; | |
entry.path = match[3]; | |
entry.code = stoi(match[4]); | |
entry.responseSize = stoi(match[5]); | |
tm tm; | |
strptime(date.c_str(), dateFormat.c_str(), &tm); | |
entry.timestamp = mktime(&tm); | |
logEntries.push_back(entry); | |
cout << "HTTP Request at " << date << ": "; | |
cout << entry.verb << " " << entry.path << ". "; | |
cout << "Response code " << entry.code << " with " << entry.responseSize << "B." << endl; | |
} | |
cout << "Done! :)" << endl; | |
return 0; | |
} |
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
compile: parser.cc | |
g++-4.9 -std=c++14 -I. -O3 -o parser parser.cc |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment