FCF 2.0 development in progress...
> > > > > > > >
[News] [C++ Libraries API] [C++ Downloads] [Donate to the project] [Contacts]

handler from class fcf::NTest::Logger::Prefix

Property: handler

Type: fcf::NTest::Logger::PrefixFunction

Class: fcf::NTest::Logger::Prefix

Package: fcfTest

File: test.hpp

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); // 4. Run the tests bool error = false; fcf::NTest::cmdRun(a_argc, a_argv, fcf::NTest::CRM_RUN, &error); return error ? 1 : 0; }

Output:

Performing the test: "HandlerDemo" -> "Logger" -> "DynamicPrefix" ... > [12:00:00 | log] Message with dynamic prefix [SUCCESS] Test completed successfully (0.000`005`123 sec) [SUCCESS] All tests were completed. Tests: 1 passed, 0 failed, 0 skipped, 1 total Duration: 0.000`005`123 sec

The handler was successfully invoked, allowing us to inject real-time data (time and level) into the log stream.