我想写入带有时间戳的日志文件。时间戳应表示从应用程序开始的时间间隔,如下所示:
1: This log message arrived after 1s of starting the application
5: This log message arrived after 5s of starting the application
然后我想在那个确切的时间间隔内读取日志消息。就像 1 秒后我将阅读第一条消息,然后当 5 秒过去时我将阅读第二条消息。
是否有任何图书馆可以让我做到这一点?我找到了一些像 easyloggingcpp 这样的图书馆可以使用时间戳保存日志文件。但是时间戳就是对应的时间。此外,我还没有找到如何在特定时间间隔阅读消息的任何方法。
有什么办法可以做到吗?
最佳答案
因此,您需要在生产者中使用一个日志类来了解应用程序的启动时间。
class Logger {
static std::chrono::steady_clock::time_point start; // program start
std::ofstream out; // log file stream
public:
Logger(const char *filename): out(filename) {}
void log(const char *msg) { // log function
std::chrono::steady_clock::time_point cur = std::chrono::steady_clock::now();
std::chrono::duration<double> d = cur - start; // delta time since program start
// prepend text message with delta time
out << int(d.count()) << " - " << msg << std::endl;
}
~Logger() {
out.close();
}
};
以下部分是单一定义规则定义,应在您的程序中恰好出现一次。即使类的定义在包含文件中,您也应该将其写在主源中
// definition of static member
std::chrono::steady_clock::time_point Logger::start = std::chrono::steady_clock::now();
你可以简单地在生产者程序中使用它:
int main() {
Logger log("foo.log");
std::chrono::duration<int> d = std::chrono::duration<int>(1);
// sleep for 1 second
std::this_thread::sleep_for(d);
log.log("After 1s");
// sleep for 4 seconds more
d = std::chrono::duration<int>(4);
std::this_thread::sleep_for(d);
log.log("After 5s");
return 0;
}
然后您需要一个阅读器从日志文件中读取每一行,从开始提取延迟并计算从最后一条消息开始的延迟(从开始开始的延迟正在增加通过构造),然后休眠当时:
int main() {
std::ifstream in("foo.log"); // log file input stream
// store program start time
std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
std::string line;
while (std::getline(in, line)) { // read log file one line at a time
std::stringstream ss(line); // parse line to extract delay
int delay;
if (! (ss >> delay)) break;
std::chrono::duration<int> d(delay);
std::this_thread::sleep_until(start + d); // wait until approriate time
// message processing (here simple display on stdout)
std::cout << line << std::endl;
}
return 0;
}
关于c++ - 在特定时间间隔读写日志c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50561505/