如何在 C++ 中自动刷新日志消息并解锁互斥量?

How to flush a log message and unlock a mutex automatically in C++?

这是我写的logger。它工作正常,但有些事情我没能做到。

uLOG(warning) << "Test log message " << 123 << uLOGE;

uLOG 锁定 C++11 互斥量并开始写入文件流。
uLOGE 刷新流并解锁互斥锁。

我想用这个语法得到相同的结果:

uLOG(warning) << "Test log message " << 123;

所以我希望在行尾自动调用刷新和解锁。

哪种方法可行?


您需要重新设计您的日志记录框架,以便 uLOG 是您实例化的 class,其析构函数执行您的 uLOGE 宏.


非常简单的例子:

struct uLOG
{
    uLOG(std::string const& type)
    {
        std::cout << "Log: " << type << " - ";
    }

    template<typename T>
    uLOG& operator<<(T const& output)
    {
        std::cout << output;
        return *this;
    }

    ~uLOG()
    {
        std::cout << " (end of log)" << std::endl;
    }
};

// ...
uLOG("warning") << "log message" << 123;

以上,在合适的程序中,应该打印

Log: warning - log message123 (end of log)

此解决方案不需要使用大括号,因此可以在单语句无大括号 if 或循环中使用。

你的第二种方法是正确的,如果正确实施它不需要大括号。你是用宏做的吗?这里不需要它们。

uLOG 应该是 returns 日志写入器 class 的临时对象的函数。正如您所概述的,它应该锁定在 ctor 中,并在 dtor 中刷新和解锁,并且还具有模板化的 operator<< 用于所有类型,它只是将调用转发到实际的日志目的地。