为了更好地监控项目运行状态,日志记录是开发过程中不可或缺的一环,Server 端则是各类功能模块的最终集成入口。
1. 日志
__FILE__ 和 __LINE__ 是 C/C++ 编译器预定义的特殊宏:
__FILE__:
它会被编译器自动替换为当前代码所在源文件的路径或文件名(字符串类型)。在日志函数中,用于记录日志输出的来源文件。例如:如果在 test.cpp 中调用 LOG1 宏,__FILE__ 会被替换为 "test.cpp",最终日志显示 [test.cpp : ...]。
__LINE__:
它会被编译器自动替换为当前代码所在的行号(整数类型)。在日志函数中,用于记录日志输出的具体行号。例如:如果 LOG1 宏调用写在 test.cpp 的第 25 行,__LINE__ 会被替换为 25,最终日志显示 [test.cpp : 25]。
下面创建一个 log1 函数来打印所需信息:
#pragma once
#include <iostream>
#include <string>
#include <ctime>
#define NORMAL 1
#define WARNING 2
#define DEBUG 3
#define FATAL 4
#define LOG1(LEVEL, MESSAGE) log1(#LEVEL, MESSAGE, __FILE__, __LINE__)
void log1(std::string level, std::string message, std::string file, int line) {
std::cout << "[" << level << "]" << "[" << time(nullptr) << "]" << "[" << message << "]" << "[" << file << " : " << line << "]" << std::endl;
}
2. server.cc
data/raw_html/raw.txt 路径下存储的是数据源,./wwwroot/ 可理解为前端网页代码目录。
queue 是要搜索的关键字,json_string 是返回给用户的搜索结果。
程序实例化一个 Searcher 类,然后调用 InitSearcher 函数。这里使用 fgets 而非 cin,因为 cin 会忽略空格,而 fgets 可以整行读取。
buffer[strlen(buffer)-1]=0; 是为了去除用户输入末尾的换行符。处理后的结果交给 query,然后调用 Search 函数,将结果存入 json_string 并输出。
#include "searcher.hpp"
#include <iostream>
#include <string>
#include <cstdio>
const std::string input = "data/raw_html/raw.txt";
const std::string root_path = "./wwwroot";
int main() {
ns_searcher::Searcher* search = new ns_searcher::Searcher();
search->InitSearcher(input);
std::string query;
std::string json_string;
char buffer[1024];
while (1) {
std::cout << "Enter Search Query: ";
// std::cin >> query;
fgets(buffer, sizeof(buffer) - 1, stdin);
if (strlen(buffer) > 0) {
buffer[strlen(buffer) - 1] = 0;
}
query = buffer;
search->Search(query, &json_string);
std::cout << json_string << std::endl;
}
return 0;
}



