如何从日志文件中抓取状态代码?(在 C++ 中)

How do I scrape status code from the log file? (in c++)

本文关键字:C++ 代码 抓取 日志 文件 状态      更新时间:2023-10-16

日志文件中的每个字符串如下所示:

44.225.84.206 - - [12/Mar/2020:07:02:43 +0530] "获取 HTTP/1.1 http://example.com/" 200 73 "-" "AWS 安全扫描程序">

我必须计算文件中的状态代码(此处为200(。

您可以通过std::regex库使用正则表达式。"".+" (\d+)"模式匹配任何带引号的字符串和空格后的任何数字。由于您的状态代码紧跟在带引号的字符串"GET http://example.com/ HTTP/1.1" 200之后,它将匹配第一个数字字符直到空格,因此 73 将不匹配。请注意,如果您的日志文件在其他任何地方都包含带引号的字符串,后跟空格和数字,它也将匹配,如果需要,请修改模式。

std::regex_search()将匹配该行并将结果存储在match中。match.str(1)将返回第一组;第一个()的内容,即 200 作为字符串。如果需要,将其转换为int

#include <fstream>
#include <iostream>
#include <regex>
#include <vector>
int main()
{
std::ifstream log_file("statlog.txt");
std::regex re("".+" (\d+)");
std::smatch match;
std::string line;
std::vector<std::string> status_code;
while(std::getline(log_file, line)) {
if(std::regex_search(line.cbegin(), line.cend(),match, re))
status_code.push_back(match.str(1));
}
for(auto& elem : status_code) std::cout  << elem << 'n';
}

这会将所有状态代码存储在字符串向量中。

当然,如果您使用的是 C++11 或更高版本,这是。