Demonstrating how to use fcf::NTest::Logger::FormatFunction to wrap log messages in decorative brackets and convert them to uppercase.
#define FCF_TEST_IMPLEMENTATION
#include <fcfTest/test.hpp>
#include <iostream>
#include <algorithm>
#include <string>
#include <regex>
FCF_TEST_DECLARE("FormatDemo", "Logger", "Decorator") {
// Trigger a log event
fcf::NTest::log() << "hello world" << std::endl;
}
std::string cleanMessage(std::string a_string) {
std::regex ansi_regex("\x1B\\[[0-?]*[ -/]*[@-~]");
std::string result = std::regex_replace(a_string, ansi_regex, "");
result.erase(result.find_last_not_of(" \t\n\r\f\v") + 1);
return result;
}
int main(int a_argc, char* a_argv[]) {
// Define a custom format function
fcf::NTest::Logger::Format format;
format.name = "decorated";
// This function will wrap the message in [MSG] and make it uppercase
fcf::NTest::Logger::FormatFunction formatFunction = []( fcf::NTest::Logger&, fcf::NTest::Logger::MessageContext& context) {
std::string msg = context.message;
// Transform to uppercase
std::transform(msg.begin(), msg.end(), msg.begin(), ::toupper);
// Clear the string of terminal control commands and the last line feed
msg = cleanMessage(msg);
// Wrap with brackets
context.message = "[<" + msg + ">]\n";
};
format.handler = formatFunction;
// We use appendFormatFunc to register our custom logic
fcf::NTest::logger().appendFormat(format);
bool error = false;
fcf::NTest::cmdRun(a_argc, a_argv, fcf::NTest::CRM_RUN, &error);
return error ? 1 : 0;
}
Output:
[<PERFORMING THE TEST: "FORMATDEMO" -> "LOGGER" -> "DECORATOR" ...>]
[< > HELLO WORLD>]
[< <term-green>[SUCCESS]</term-green> TEST COMPLETED SUCCESSFULLY (0.000`130`403 SEC)>]
[<>]
[<<term-green>[SUCCESS]</term-green> ALL TESTS WERE COMPLETED.>]
[<TESTS: 1 PASSED, 0 FAILED, 0 SKIPPED, 1 TOTAL>]
[<DURATION: 0.000`130`403 SEC>]
The application must be run by specifying the format via a command-line parameter:
app --test-format "decorated"
The fcf::NTest::Logger::FormatFunction successfully intercepted the message "hello world", transformed it to uppercase, and added the decorative brackets before it reached the output stream.