Type: fcf::NTest::Logger::PrefixFunction
Class: fcf::NTest::Logger::Prefix
Package: fcfTest
File:
test.hpp
( link_to_the_declaration_in_the_file )
Available from version: 1.2.1
A callback function used to dynamically generate a prefix string for log messages.
The handler property is a functional callback that allows for the dynamic generation of a prefix string. Unlike the static prefix property, the handler is invoked for every log message, providing access to the full fcf::NTest::Logger::MessageContext.
This enables advanced logging features such as:
- Injecting dynamic information like timestamps or thread IDs.
- Formatting the prefix based on the current log level or message category.
- Accessing user-defined metadata attached to the log via the data property.
Example: Dynamic Timestamp and Level Prefix
Demonstrating how to use the handler to create a dynamic prefix that includes a timestamp and the current log level.
#define FCF_TEST_IMPLEMENTATION
#include <fcfTest/test.hpp>
#include <iostream>
#include <ctime>
#include <iomanip>
FCF_TEST_DEFINE("HandlerDemo", "Logger", "DynamicPrefix") {
// Trigger a log message to see the dynamic prefix in action
fcf::NTest::log() << "Message with dynamic prefix" << std::endl;
FCF_TEST(true);
}
int main(int a_argc, char* a_argv[]) {
fcf::NTest::Logger& logger = fcf::NTest::logger();
// 1. Define a custom prefix structure
fcf::NTest::Logger::Prefix prefix;
prefix.name = "dynamic-info";
prefix.multiLine = false;
prefix.category = fcf::NTest::LMC_ALL;
// 2. Implement the handler callback
prefix.handler = []( fcf::NTest::Logger&, fcf::NTest::Logger::MessageContext& a_context) {
// Get current system time
auto time = std::time(nullptr);
auto localTime = std::localtime(&time);
// Return a formatted string containing timestamp and log level
return (std::stringstream()
<< "["
<< std::put_time(localTime, "%H:%M:%S")
<< " | "
<< fcf::NTest::Logger::toLevelStr(a_context.level)
<< "] ").str();
};
// 3. Register the prefix with the logger
logger.appendPrefix(prefix, true);
// 4. Run the tests
bool error = false;
fcf::NTest::cmdRun(a_argc, a_argv, fcf::NTest::CRM_RUN, &error);
return error ? 1 : 0;
}
Output:
[08:17:08 | log] Performing the test: "HandlerDemo" -> "Logger" -> "DynamicPrefix" ...
[08:17:08 | log] > Message with dynamic prefix
[08:17:08 | log] [SUCCESS] Test completed successfully (0.000`019`488 sec)
[08:17:08 | log]
[08:17:08 | log] [SUCCESS] All tests were completed.
[08:17:08 | log] Tests: 1 passed, 0 failed, 0 skipped, 1 total
[08:17:08 | log] Duration: 0.000`019`488 sec
The handler was successfully invoked, allowing us to inject real-time data (time and level) into the log stream.