Add wide character support to wincolor_sink #3013
Closed
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Add wide character output support to
wincolor_sink
that's used as the default sink on Windows.This uses the
SPDLOG_WCHAR_TO_UTF8_SUPPORT
define to enable this functionality much like in the msvc_sink.The problem it solves is incorrect output in the Windows console when UTF8 characters are encountered in the string.
For example when outputting
std::chrono::microsecond
values like:log("Thing took {}", std::chrono::microsecond(1))
. It ends up printingThing took 1µs
rather than the expectedThing took 1µs
.The issue is because fmt and hence spdlog create strings of UTF8 characters, whereas the Windows console expects the output to be ASCII with a specified codepage. Therefore converting the text to wide characters and outputting with
WriteConsoleW
fixes the issue.However an alternative solution is to call
SetConsoleOutputCP(CP_UTF8)
at the start of your program to set the codepage of the console to UTF8. This does set the codepage for the console that's running, so the change will persist after the program exits, therefore more code needs to be added to retrieve the existing codepage and restore it at the end of the program. As such I don't think that code is appropriate to have in a library. Other developers can still implement codepage switching in their applications if they so choose, and in that case they do not need to enableSPDLOG_WCHAR_TO_UTF8_SUPPORT
.I also have to note that this doesn't change the
WriteFile
based output for when the program is not actually writing to the console but to a file or memory instead. The main place that affects me is in the test explorer window in Visual Studio where the log output is not treated as UTF8. The previous pull request had this erroneous change.You can squash the two commits into one.