Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c++ log

作者:剑歌踏天下   发布日期:2026-06-14   浏览:46

#include <iostream>
#include <fstream>
#include <string>
#include <ctime>

class Logger {
public:
    Logger(const std::string& filename) : logFile(filename, std::ios::out) {
        if (!logFile.is_open()) {
            std::cerr << "Unable to open log file: " << filename << std::endl;
        }
    }

    ~Logger() {
        if (logFile.is_open()) {
            logFile.close();
        }
    }

    void log(const std::string& message) {
        if (logFile.is_open()) {
            logFile << getCurrentTime() << " - " << message << std::endl;
        } else {
            std::cerr << "Log file is not open." << std::endl;
        }
    }

private:
    std::ofstream logFile;

    std::string getCurrentTime() {
        std::time_t now = std::time(nullptr);
        char buf[20];
        std::strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", std::localtime(&now));
        return std::string(buf);
    }
};

int main() {
    Logger logger("app.log");

    logger.log("Application started.");
    logger.log("This is a test log message.");

    return 0;
}

解释说明

  1. 类定义

    • Logger 类用于管理日志文件的打开、关闭和写入操作。
  2. 构造函数

    • 接受一个文件名作为参数,尝试打开该文件以进行写入操作。如果文件无法打开,则输出错误信息。
  3. 析构函数

    • 确保在对象销毁时关闭日志文件。
  4. log 方法

    • 将传入的消息写入日志文件,并在消息前加上当前时间戳。如果文件未打开,则输出错误信息。
  5. getCurrentTime 方法

    • 获取当前系统时间并格式化为字符串,格式为 YYYY-MM-DD HH:MM:SS
  6. main 函数

    • 创建一个 Logger 对象,指定日志文件名为 app.log
    • 调用 log 方法记录两条日志消息。

这个示例展示了如何使用 C++ 实现一个简单的日志记录功能。

上一篇:c++ string转char

下一篇:c++ map添加元素的方法

大家都在看

c++闭包

c++向上取整的代码

c++单引号和双引号的区别

c++ 注释

c++如何判断素数

c++怎么输入字符串

c++字符串切片

c++ functional

c++框架代码

c++格式化字符串

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站