c++ - 如何创建像 std::cout 这样的函数?

标签 c++ debugging logging cout

我正在为我的项目创建自己的日志实用程序,我想创建一个类似于 iostream 的 std::cout 的函数,以记录到文件并打印到控制台。

这是我想要的:

enum
{
    debug, error, warning, info
};

LOG(level) << "test"; // level - from the above enum

结果应该是这样的:

int iPlayerID = 1337;
LOG(info) << "Player " << iPlayerID << "Connected";

[2015 年 1 月 29 日星期四 18:32:11] [信息] Player 1337 已连接

最佳答案

std::cout不是函数,它是 std::ostream 类型的对象重载 operator<< .

如何做的快速草图:

enum Level {
    debug, error, warning, info
};

struct Logger {
    std::ostream* stream;  // set this in a constructor to point
                           // either to a file or console stream
    Level debug_level;
public:
    Logger& operator<<(const std::string& msg)
    {
        *stream << msg; // also print the level etc.
        return *this;
    }

    friend Logger& log(Logger& logger, Level n);
    {
        logger.debug_level = n;
        return logger;
    }
};

Ant 然后像这样使用它

Logger l;
log(l, debug) << "test";

关于c++ - 如何创建像 std::cout 这样的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28217643/

相关文章:

linux - 如何配置 ddd 以使用另一个 gdb 而不是默认 gdb

javascript - 使用 Firefox 将 JavaScript 控制台记录到日志文件中

javascript - 查看 JS 中调用了哪些方法/事件

C++ : initialize static member large array

c++ - 模板函数中带有 vector<std::string> 迭代器的 BadPtr

c++ - 在 C++ 中无效使用列表迭代器

c++ - 单击“打印”按钮后,Qt 打印对话框重新出现

python - 使用 pdb 附加进程

wcf - 如何从代码而不是应用程序配置文件启用 WCF 消息日志记录

java - java.util.logging.Logger类的info()方法是I/O操作吗?