Skip to content

Instantly share code, notes, and snippets.

@jirojo2 jirojo2/Makefile
Created Oct 2, 2015

Embed
What would you like to do?
Some experiment for casual log parsing for @SuperBuker
#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;
}
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
You can’t perform that action at this time.