nmos-cpp: Logging Boost error messages as UTF-8

By default Boost error messages when using Visual Studio are ANSI encoded and not UTF-8. To force Boost to emmit strings in UTF-8 the #define BOOST_SYSTEM_USE_UTF8 is needed. It could easily be added to Development/cmake/NmosCppCommon.cmake after line 147 like this: add_definitions(/DBOOST_SYSTEM_USE_UTF8)

Unfortunately the console also needs a hint that printed text is UTF-8. I had to fiddle a little bit, but finally I found a portable solution:

#include <clocale>

static bool make_utf8()
{
    std::string locale = setlocale(LC_CTYPE, "");
    if (!locale.empty()) {
        auto dot = locale.find_last_of('.');
        if (dot != std::string::npos) {
            locale = locale.substr(0, dot) + ".utf8";
            char* result = setlocale(LC_CTYPE, locale.c_str());
            return result != nullptr;
        }
    }
    return false;
}

After initialising the log:

if (!make_utf8())
{
    slog::log<slog::severities::error>(gate, SLOG_FLF) << "Setting console to UTF-8 mode failed";
}

Tested under Windows and Linux.

About this issue

  • Original URL
  • State: open
  • Created 4 years ago
  • Comments: 15 (8 by maintainers)

Most upvoted comments