温馨提示×

利用C++时间戳实现日志记录功能

c++
小樊
115
2024-08-19 20:40:34
栏目: 编程语言
C++开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在C++中,可以使用time库来获取当前时间戳,并将时间戳转换成可读的日期时间格式,然后将日志记录到文件中。以下是一个简单的示例代码:

#include <iostream>
#include <fstream>
#include <ctime>
#include <iomanip>

void log(const std::string& message) {
    std::ofstream file("log.txt", std::ios_base::app);
    if (file.is_open()) {
        std::time_t now = std::time(nullptr);
        char timestamp[100];
        std::strftime(timestamp, sizeof(timestamp), "%Y-%m-%d %H:%M:%S", std::localtime(&now));
        
        file << "[" << timestamp << "] " << message << std::endl;
        file.close();
    } else {
        std::cerr << "Error opening log file" << std::endl;
    }
}

int main() {
    log("Log message 1");
    log("Log message 2");
    
    return 0;
}

这段代码定义了一个log函数,它将传入的消息与当前时间戳一起写入到log.txt文件中。在main函数中,我们可以调用log函数来记录日志消息。每次调用log函数时,会追加一条日志消息到文件中,格式为[YYYY-MM-DD HH:MM:SS] message

请注意,在实际应用中可能需要添加一些错误处理和日志级别等功能来提高日志记录的灵活性和可用性。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:unix时间戳在c++日志记录中的应用有哪些

0