Boost.Log忽略重载的流插入运算符

时间:2014-04-10 09:38:32

标签: c++ boost operator-overloading boost-log widestring

我有一个我希望以某种方式出现在日志中的课程,因此我已经重载了<<运算符:

class CWindowClassId
{
public:
    // ...
    friend std::wostream& operator<< (std::wostream& os, CWindowClassId const& classId);
}

在日志流中插入上面的类:

// ...
CWindowClassId classId(hWindow);
BOOST_LOG_TRIVIAL(debug) << "Window created, class = " << classId;

导致编译错误:

Error   1   error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'const Sandbox::CWindowClassId' (or there is no acceptable conversion)    C:\local\boost_1_55_0\boost\log\utility\formatting_ostream.hpp  710

我知道错误在于,我为宽字符串重载<<。当我使用ostream而不是wostream时,一切都很好,但我真的想使用宽字符串版本。

我试图为接收器设置区域设置:

shared_ptr<log::sinks::synchronous_sink<log::sinks::text_file_backend> > sink = log::add_file_log("log.txt");
sink->imbue(boost::locale::generator()("en_US.UTF-8"));

在任何与日志相关的包含之前定义BOOST_LOG_USE_WCHAR_T

我可以做些什么来使用宽字符串<<运算符进行日志记录工作吗?

我正在使用Boost 1.55.0。

1 个答案:

答案 0 :(得分:1)

我认为你不能用BOOST_LOG_TRIVIAL做到这一点。琐碎的记录器使用基础boost::sources::logger而不是boost::sources::wlogger,您可以从boost源文件中的trivial.hpp和trivial.cpp看到,我无法看到我们如何更改它除非我们修改源代码。如果您使用wlogger,它会起作用。这是一个例子:

#include <iostream>
#include <string>
#include <boost/log/sources/logger.hpp>
#include <boost/log/common.hpp>

namespace src = boost::log::sources;

class CWindowClassId
{
public:
    // ...
    friend std::wostream& operator<< (std::wostream& os, CWindowClassId const& classId)
    {
        os << classId.ws;
        return os;
    }
public:
    std::wstring ws;
};

int main(int argc, char* argv[])
{
    src::wlogger lg;
    CWindowClassId id;
    id.ws = L"wide char";
    BOOST_LOG(lg) << "Hello, World! This is a wide character message."<<id;
    return 0;
}