-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLogParser.cpp
More file actions
89 lines (74 loc) · 2.57 KB
/
LogParser.cpp
File metadata and controls
89 lines (74 loc) · 2.57 KB
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
#include "LogParser.h"
#include "Utils.h"
#include <fstream>
#include <sstream>
#include <iostream>
#include <regex>
std::vector<LogEntry> LogParser::parseFile(const std::string& filepath) {
std::vector<LogEntry> entries;
std::ifstream file(filepath);
if (!file.is_open()) {
std::cerr << Utils::RED << "Error: Cannot open file: " << filepath << Utils::RESET << "\n";
return entries;
}
std::string line;
int lineNum = 0;
while (std::getline(file, line)) {
lineNum++;
totalLines++;
line = Utils::trim(line);
if (line.empty() || line[0] == '#') {
skippedLines++;
continue;
}
LogEntry entry = parseLine(line, lineNum);
if (entry.level != LogLevel::UNKNOWN) {
entries.push_back(entry);
} else {
skippedLines++;
}
}
return entries;
}
LogEntry LogParser::parseLine(const std::string& line, int lineNumber) {
LogEntry entry;
entry.lineNumber = lineNumber;
entry.level = LogLevel::UNKNOWN;
if (parseStandardFormat(line, entry)) return entry;
if (parseSimpleFormat(line, entry)) return entry;
return entry;
}
bool LogParser::parseStandardFormat(const std::string& line, LogEntry& entry) {
// Format: [2024-01-15 10:30:45] [ERROR] [source] message
// or: 2024-01-15 10:30:45 ERROR source: message
static const std::regex standardRegex(
R"(\[?(\d{4}-\d{2}-\d{2}[\sT]\d{2}:\d{2}:\d{2}(?:\.\d+)?)\]?\s+\[?(\w+)\]?\s+(?:\[([^\]]+)\]\s+)?(.+))"
);
std::smatch match;
if (std::regex_match(line, match, standardRegex)) {
entry.timestamp = Utils::trim(match[1].str());
entry.level = LogEntry::levelFromString(match[2].str());
entry.source = match[3].str().empty() ? "app" : Utils::trim(match[3].str());
entry.message = Utils::trim(match[4].str());
if (entry.level != LogLevel::UNKNOWN) return true;
}
return false;
}
bool LogParser::parseSimpleFormat(const std::string& line, LogEntry& entry) {
// Format: ERROR: message or [ERROR] message
static const std::regex simpleRegex(
R"(\[?(\w+)\]?:\s+(.+))"
);
std::smatch match;
if (std::regex_match(line, match, simpleRegex)) {
LogLevel lvl = LogEntry::levelFromString(match[1].str());
if (lvl != LogLevel::UNKNOWN) {
entry.level = lvl;
entry.timestamp = "N/A";
entry.source = "app";
entry.message = Utils::trim(match[2].str());
return true;
}
}
return false;
}