Type: fcf::NTest::SharedPtrAny*
Class: fcf::NTest::Logger::MessageContext
Package: fcfTest
File: test.hpp
Available from version: 1.1.14
A pointer to user-defined metadata associated with the current stream and formatter.
The data property is a pointer to a fcf::NTest::SharedPtrAny object. This provides a mechanism for attaching arbitrary, type-erased user data to a log message. This data is extremely useful for advanced formatters or prefixes that need to access complex objects (like custom state, database connections, or user-defined structures) that were passed along with the logging call.
A dedicated fcf::NTest::SharedPtrAny object is created for each fcf::NTest::Logger::Format - fcf::NTest::Logger::OutputTarget pair.
Example: Passing Custom Data to Formatters
Demonstrating how to attach a custom object to a log message and retrieve it within a fcf::NTest::Logger::Format handler using the data property.
#define FCF_TEST_IMPLEMENTATION
#include <fcfTest/test.hpp>
// A custom structure to be passed as metadata
struct UserMetadata {
std::string username;
int userId;
};
FCF_TEST_DEFINE("DataDemo", "Logger", "MetadataTest") {
fcf::NTest::log() << "Action performed by user." << std::endl;
}
void initialize() {
// Define a format that extracts and prints the metadata
fcf::NTest::Logger::Format format;
format.name = "metadata-format";
format.handler = []( fcf::NTest::Logger&, fcf::NTest::Logger::MessageContext& a_context) {
// Cast the type-erased pointer back to our known type
UserMetadata* meta = a_context.data->cast<UserMetadata>();
if (meta) {
a_context.message = " [User: " + meta->username + " (ID: " + std::to_string(meta->userId) + ")] " + a_context.message;
}
};
// Specify the function that will be called to initialize
// the format data when outputting to a separate thread for the first time
format.dataFactory = [](fcf::NTest::Logger&, fcf::NTest::Logger::OutputTarget&){
return fcf::NTest::SharedPtrAny::make<UserMetadata>(UserMetadata{"JohnDoe", 1234});
};
fcf::NTest::logger().appendFormat(format);
}
int main(int a_argc, char* a_argv[]) {
initialize();
bool error = false;
fcf::NTest::cmdRun(a_argc, a_argv, fcf::NTest::CRM_RUN, &error);
return error ? 1 : 0;
}
Output:
[User: JohnDoe (ID: 1234)] Performing the test: "DataDemo" -> "Logger" -> "MetadataTest" ...
[User: JohnDoe (ID: 1234)] > Action performed by user.
[User: JohnDoe (ID: 1234)] [SUCCESS] Test completed successfully (0.000`006`107 sec)
[User: JohnDoe (ID: 1234)]
[User: JohnDoe (ID: 1234)] [SUCCESS] All tests were completed.
[User: JohnDoe (ID: 1234)] Tests: 1 passed, 0 failed, 0 skipped, 1 total
[User: JohnDoe (ID: 1234)] Duration: 0.000`006`107 sec
Note: The data pointer is typically populated by the fcf::NTest::Logger when it processes a log request that includes associated metadata.
The application must be run by specifying the format via a command-line parameter:
app --test-format "metadata-format"