Log: color console output by default (NO_COLOR opt-out)

This commit is contained in:
faumaray committed 2026-12-04 08:20:14 +03:00
1 parent 3ce62c9cbd
commit b3c1246291
2 files changed
+30 -4

No files matched your search

+10 -4
View File
@@ -4,6 +4,7 @@
#include <Void/Stacktrace/Color.hpp>
#endif
#include <cstdlib>
#include <iostream>
#include <ostream>
@@ -15,12 +16,17 @@ namespace Void::Logging
ColorPolicy console_default_policy()
{
ColorPolicy p = ColorPolicy::defaults();
// Colored by default, with the standard opt-outs: NO_COLOR for
// the environment and the Stacktrace global toggle when present.
bool enabled = true;
if (const char* no_color = std::getenv("NO_COLOR");
no_color != nullptr && *no_color != '\0') {
enabled = false;
}
#ifdef VOID_HAS_STACKTRACE
// Honor the global color toggle when Stacktrace is present.
p.enabled = Void::Stacktrace::Color::g_color_enabled;
#else
p.enabled = false;
enabled = enabled && Void::Stacktrace::Color::g_color_enabled;
#endif
p.enabled = enabled;
return p;
}
} // namespace
+20
View File
@@ -24,6 +24,26 @@ class ConsoleLoggerTests : public Void::Testing::Fixture
Void::Testing::expect(content.find("Info") != std::string::npos);
}
Void::Testing::Test colors_by_default_with_no_color_opt_out()
{
::unsetenv("NO_COLOR");
{
std::ostringstream out;
Void::Logging::ConsoleLogger log{out, Void::Logging::Mode::Immediate};
log.error("colored");
Void::Testing::expect(out.str().find("\x1b[") != std::string::npos);
}
::setenv("NO_COLOR", "1", 1);
{
std::ostringstream out;
Void::Logging::ConsoleLogger log{out, Void::Logging::Mode::Immediate};
log.error("plain");
Void::Testing::expect(out.str().find("\x1b[") == std::string::npos);
Void::Testing::expect(out.str().find("plain") != std::string::npos);
}
::unsetenv("NO_COLOR");
}
Void::Testing::Test level_filtering()
{
std::ostringstream out;