Boost.Log
Comprehensive C++ logging framework provided as part of Boost library collection. Offers advanced customization and enterprise-level features. Possesses powerful configuration options and extensibility to handle complex requirements.
Library
Boost.Log
Overview
Boost.Log is a comprehensive C++ logging framework provided as part of the Boost library collection. It offers advanced customization and enterprise-level features with powerful configuration options and extensibility to handle complex requirements. Supporting multiple log levels, filtering, formatting, and simultaneous output to multiple destinations (files, console, syslog, etc.), it provides thread-safe operations, asynchronous log processing, and log rotation capabilities, delivering a reliable logging solution for large-scale and complex C++ projects.
Details
Boost.Log 2025 edition maintains high evaluation as a choice for large-scale and complex C++ projects. Adoption continues in enterprise environments due to the reliability and maturity of the Boost ecosystem, providing stability and backward compatibility through over 15 years of development experience. With configuration file-based flexible setup systems, rich sink (output destination) options, and support for implementing custom filters and formatters, it addresses enterprise-level requirements. Enhanced CMake support, utilization of modern C++ features, and cross-platform compatibility (Windows, Linux, macOS) adapt to contemporary development environments.
Key Features
- Comprehensive logging system: Advanced control through multiple sinks, filters, and formatters
- Enterprise ready: Configuration file-based management and production environment stability
- Thread-safe: Safe logging operations and asynchronous processing support
- Rich output destinations: Files, console, syslog, Windows event log, etc.
- High customizability: Implementation support for custom sinks, filters, and formatters
- Boost ecosystem: Integration with other Boost libraries and consistent design
Pros and Cons
Pros
- Reliability of Boost library collection and mature development experience of over 15 years
- Rich enterprise-level features and advanced customization capabilities
- Runtime configuration changes through configuration files and production environment flexibility
- Thread-safe operations and high performance through asynchronous processing
- Rich output destination options and simultaneous output support to multiple sinks
- Comprehensive documentation and community support
Cons
- Configuration complexity makes it overkill for small-scale projects
- Large header file sizes impact compilation time
- High learning curve, unsuitable for simple logging needs
- Many dependencies, inappropriate for environments prioritizing minimal binary size
- Complex CMake configuration and initial setup overhead
- Verbose syntax compared to modern C++ libraries
Reference Pages
Usage Examples
Installation and Basic Setup
// Boost.Log installation (Ubuntu/Debian)
// sudo apt-get install libboost-log-dev
// Windows (vcpkg)
// vcpkg install boost-log
// CMakeLists.txt example
/*
cmake_minimum_required(VERSION 3.15)
project(BoostLogExample)
find_package(Boost REQUIRED COMPONENTS log log_setup)
add_executable(example main.cpp)
target_link_libraries(example
Boost::log
Boost::log_setup
${CMAKE_THREAD_LIBS_INIT}
)
# Windows specific
if(WIN32)
target_link_libraries(example ws2_32 mswsock)
endif()
*/
#include <boost/log/core.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/utility/setup/file.hpp>
#include <boost/log/utility/setup/console.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>
namespace logging = boost::log;
namespace src = boost::log::sources;
namespace sinks = boost::log::sinks;
namespace keywords = boost::log::keywords;
int main() {
// Basic initialization
logging::add_common_attributes();
// Console output setup
logging::add_console_log(
std::cout,
keywords::format = "[%TimeStamp%] [%Severity%] %Message%"
);
// Basic log output
BOOST_LOG_TRIVIAL(trace) << "Application started";
BOOST_LOG_TRIVIAL(debug) << "Debug information";
BOOST_LOG_TRIVIAL(info) << "Information message";
BOOST_LOG_TRIVIAL(warning) << "Warning message";
BOOST_LOG_TRIVIAL(error) << "Error message";
BOOST_LOG_TRIVIAL(fatal) << "Fatal error";
return 0;
}
Basic Log Levels and Filtering
#include <boost/log/core.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/utility/setup/file.hpp>
#include <boost/log/utility/setup/console.hpp>
namespace logging = boost::log;
namespace trivial = boost::log::trivial;
class LogManager {
public:
static void initialize(trivial::severity_level level = trivial::info) {
// Global filter setup
logging::core::get()->set_filter(
trivial::severity >= level
);
// Console output setup
logging::add_console_log(
std::cout,
boost::log::keywords::format =
"[%TimeStamp%] [%ThreadID%] [%Severity%] %Message%"
);
// File output setup
logging::add_file_log(
boost::log::keywords::file_name = "application_%N.log",
boost::log::keywords::rotation_size = 10 * 1024 * 1024, // 10MB
boost::log::keywords::time_based_rotation =
sinks::file::rotation_at_time_point(0, 0, 0), // Daily
boost::log::keywords::format =
"[%TimeStamp%] [%ThreadID%] [%Severity%] %Message%"
);
logging::add_common_attributes();
}
// Dynamic log level change
static void setLogLevel(trivial::severity_level level) {
logging::core::get()->set_filter(
trivial::severity >= level
);
}
// Statistics information
static void logStatistics() {
auto core = logging::core::get();
BOOST_LOG_TRIVIAL(info) << "Log core configuration completed";
}
};
// Usage example
void demonstrateLogLevels() {
// Initialize (INFO level and above only)
LogManager::initialize(trivial::info);
BOOST_LOG_TRIVIAL(trace) << "Trace - not displayed";
BOOST_LOG_TRIVIAL(debug) << "Debug - not displayed";
BOOST_LOG_TRIVIAL(info) << "Info - displayed";
BOOST_LOG_TRIVIAL(warning) << "Warning - displayed";
BOOST_LOG_TRIVIAL(error) << "Error - displayed";
// Change to debug level
LogManager::setLogLevel(trivial::debug);
BOOST_LOG_TRIVIAL(debug) << "Debug - now displayed";
// Custom message
BOOST_LOG_TRIVIAL(info) << "UserID: " << 12345 << ", Operation: Login successful";
}
// Thread-safe logging example
void threadSafeLogging() {
std::vector<std::thread> threads;
for (int i = 0; i < 5; ++i) {
threads.emplace_back([i]() {
for (int j = 0; j < 100; ++j) {
BOOST_LOG_TRIVIAL(info)
<< "Thread " << i << " - Message " << j;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
});
}
for (auto& t : threads) {
t.join();
}
}
int main() {
demonstrateLogLevels();
threadSafeLogging();
return 0;
}
Configuration File-Based Advanced Setup
// settings.ini file example
/*
[Core]
Filter="%Severity% >= debug"
[Sinks.Console]
Destination=Console
Format="[%TimeStamp%] [%Severity%] %Message%"
Filter="%Severity% >= info"
[Sinks.File]
Destination=TextFile
FileName=application.log
AutoFlush=true
Format="[%TimeStamp%] [%ThreadID%] [%Severity%] [%Channel%] %Message%"
Filter="%Severity% >= debug"
[Sinks.ErrorFile]
Destination=TextFile
FileName=errors.log
AutoFlush=true
Format="[%TimeStamp%] [%ThreadID%] [%Severity%] %Message%"
Filter="%Severity% >= error"
*/
#include <boost/log/utility/setup/from_settings.hpp>
#include <boost/log/utility/setup/settings_parser.hpp>
#include <boost/log/sources/severity_channel_logger.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
namespace src = boost::log::sources;
namespace logging = boost::log;
class ConfigurableLogger {
private:
src::severity_channel_logger<logging::trivial::severity_level, std::string> logger_;
public:
ConfigurableLogger(const std::string& channel = "General") {
logger_.channel(channel);
}
// Initialize from configuration file
static void initializeFromFile(const std::string& configFile) {
try {
boost::property_tree::ptree pt;
boost::property_tree::ini_parser::read_ini(configFile, pt);
logging::init_from_settings(pt);
logging::add_common_attributes();
BOOST_LOG_TRIVIAL(info) << "Logging configuration loaded from '" << configFile << "'";
} catch (const std::exception& e) {
std::cerr << "Configuration file loading error: " << e.what() << std::endl;
// Fallback configuration
logging::add_console_log(
std::cout,
boost::log::keywords::format = "[%TimeStamp%] [%Severity%] %Message%"
);
logging::add_common_attributes();
}
}
// Channel-based log output
template<typename T>
void log(logging::trivial::severity_level level, const T& message) {
BOOST_LOG_SEV(logger_, level) << message;
}
// Convenience methods
template<typename T>
void trace(const T& msg) { log(logging::trivial::trace, msg); }
template<typename T>
void debug(const T& msg) { log(logging::trivial::debug, msg); }
template<typename T>
void info(const T& msg) { log(logging::trivial::info, msg); }
template<typename T>
void warning(const T& msg) { log(logging::trivial::warning, msg); }
template<typename T>
void error(const T& msg) { log(logging::trivial::error, msg); }
template<typename T>
void fatal(const T& msg) { log(logging::trivial::fatal, msg); }
};
// Application class example
class Application {
private:
ConfigurableLogger authLogger_;
ConfigurableLogger dbLogger_;
ConfigurableLogger apiLogger_;
public:
Application()
: authLogger_("Auth")
, dbLogger_("Database")
, apiLogger_("API") {
}
void run() {
authLogger_.info("Authentication service started");
dbLogger_.info("Database connection established");
apiLogger_.info("API server started");
// Business logic execution
simulateUserAuthentication();
simulateDatabaseOperations();
simulateAPIRequests();
authLogger_.info("Authentication service stopped");
dbLogger_.info("Database connection closed");
apiLogger_.info("API server stopped");
}
private:
void simulateUserAuthentication() {
authLogger_.debug("User authentication process started");
try {
// Authentication process simulation
authLogger_.info("User 'user123' login successful");
} catch (const std::exception& e) {
authLogger_.error("Authentication error: " + std::string(e.what()));
}
}
void simulateDatabaseOperations() {
dbLogger_.debug("Database operation started");
try {
dbLogger_.info("SELECT query executed: users table");
dbLogger_.info("Query execution time: 25ms");
} catch (const std::exception& e) {
dbLogger_.error("Database error: " + std::string(e.what()));
}
}
void simulateAPIRequests() {
apiLogger_.debug("API request processing started");
apiLogger_.info("GET /api/users - 200 OK - 45ms");
apiLogger_.warning("POST /api/users - Rate limit warning");
apiLogger_.error("DELETE /api/users/invalid - 404 Not Found");
}
};
int main() {
try {
// Initialize from configuration file
ConfigurableLogger::initializeFromFile("settings.ini");
// Run application
Application app;
app.run();
} catch (const std::exception& e) {
std::cerr << "Application error: " << e.what() << std::endl;
return 1;
}
return 0;
}
Custom Sink and Formatter Implementation
#include <boost/log/sinks/sync_frontend.hpp>
#include <boost/log/sinks/text_ostream_backend.hpp>
#include <boost/log/sources/record_ostream.hpp>
#include <boost/log/support/date_time.hpp>
#include <boost/log/expressions/formatters/date_time.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <fstream>
#include <iomanip>
namespace logging = boost::log;
namespace sinks = boost::log::sinks;
namespace src = boost::log::sources;
namespace expr = boost::log::expressions;
namespace attrs = boost::log::attributes;
namespace keywords = boost::log::keywords;
// Custom sink implementation example (JSON format file output)
class JsonFileSink {
public:
typedef sinks::synchronous_sink<sinks::text_ostream_backend> sink_t;
static boost::shared_ptr<sink_t> create(const std::string& fileName) {
auto backend = boost::make_shared<sinks::text_ostream_backend>();
// Add file stream
backend->add_stream(
boost::shared_ptr<std::ostream>(new std::ofstream(fileName))
);
// Auto flush setup
backend->auto_flush(true);
auto sink = boost::make_shared<sink_t>(backend);
// Custom JSON formatter setup
sink->set_formatter(&JsonFileSink::jsonFormatter);
return sink;
}
private:
static void jsonFormatter(logging::record_view const& rec,
logging::formatting_ostream& strm) {
auto timestamp = rec[expr::attr<boost::posix_time::ptime>("TimeStamp")];
auto severity = rec[expr::attr<logging::trivial::severity_level>("Severity")];
auto threadId = rec[expr::attr<attrs::current_thread_id::value_type>("ThreadID")];
strm << "{"
<< "\"timestamp\":\"" << timestamp << "\","
<< "\"severity\":\"" << severity << "\","
<< "\"thread_id\":\"" << threadId << "\","
<< "\"message\":\"" << rec[expr::smessage] << "\""
<< "}" << std::endl;
}
};
// Custom structured logger implementation
class StructuredLogger {
private:
src::severity_logger<logging::trivial::severity_level> logger_;
boost::shared_ptr<JsonFileSink::sink_t> jsonSink_;
public:
StructuredLogger() {
setupSinks();
}
// Structured log entry
struct LogEntry {
std::string operation;
std::string userId;
std::string resource;
int statusCode = 0;
long duration = 0;
std::map<std::string, std::string> metadata;
std::string toMessage() const {
std::ostringstream oss;
oss << "operation=" << operation
<< " user_id=" << userId
<< " resource=" << resource
<< " status=" << statusCode
<< " duration=" << duration << "ms";
for (const auto& pair : metadata) {
oss << " " << pair.first << "=" << pair.second;
}
return oss.str();
}
};
void logOperation(const LogEntry& entry,
logging::trivial::severity_level level = logging::trivial::info) {
BOOST_LOG_SEV(logger_, level) << entry.toMessage();
}
// Convenience methods
void logHttpRequest(const std::string& method, const std::string& path,
int statusCode, long durationMs, const std::string& userId = "") {
LogEntry entry;
entry.operation = "http_request";
entry.userId = userId;
entry.resource = method + " " + path;
entry.statusCode = statusCode;
entry.duration = durationMs;
auto level = (statusCode >= 400) ? logging::trivial::warning : logging::trivial::info;
if (statusCode >= 500) level = logging::trivial::error;
logOperation(entry, level);
}
void logDatabaseQuery(const std::string& query, long durationMs,
bool success = true, const std::string& error = "") {
LogEntry entry;
entry.operation = "database_query";
entry.resource = query.substr(0, 50) + (query.length() > 50 ? "..." : "");
entry.duration = durationMs;
entry.statusCode = success ? 200 : 500;
if (!error.empty()) {
entry.metadata["error"] = error;
}
auto level = success ? logging::trivial::debug : logging::trivial::error;
logOperation(entry, level);
}
void logBusinessEvent(const std::string& event, const std::string& userId,
const std::map<std::string, std::string>& data = {}) {
LogEntry entry;
entry.operation = "business_event";
entry.userId = userId;
entry.resource = event;
entry.metadata = data;
logOperation(entry, logging::trivial::info);
}
private:
void setupSinks() {
// JSON format file output
jsonSink_ = JsonFileSink::create("structured_logs.json");
logging::core::get()->add_sink(jsonSink_);
// Standard console output
auto consoleSink = logging::add_console_log(
std::cout,
keywords::format = "[%TimeStamp%] [%Severity%] %Message%"
);
// Add common attributes
logging::add_common_attributes();
}
};
// Performance monitoring logger
class PerformanceLogger {
private:
StructuredLogger& logger_;
std::string operation_;
std::chrono::high_resolution_clock::time_point startTime_;
std::string userId_;
public:
PerformanceLogger(StructuredLogger& logger, const std::string& operation,
const std::string& userId = "")
: logger_(logger), operation_(operation), userId_(userId) {
startTime_ = std::chrono::high_resolution_clock::now();
// Operation start log
StructuredLogger::LogEntry entry;
entry.operation = operation_ + "_start";
entry.userId = userId_;
logger_.logOperation(entry, logging::trivial::debug);
}
~PerformanceLogger() {
auto endTime = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(
endTime - startTime_).count();
// Operation complete log
StructuredLogger::LogEntry entry;
entry.operation = operation_ + "_complete";
entry.userId = userId_;
entry.duration = duration;
auto level = (duration > 1000) ? logging::trivial::warning : logging::trivial::debug;
logger_.logOperation(entry, level);
}
};
// Usage example
class WebService {
private:
StructuredLogger logger_;
public:
void handleUserRequest(const std::string& userId, const std::string& endpoint) {
PerformanceLogger perf(logger_, "handle_user_request", userId);
auto start = std::chrono::high_resolution_clock::now();
try {
// Authentication
if (!authenticateUser(userId)) {
logger_.logHttpRequest("POST", endpoint, 401,
getDuration(start), userId);
return;
}
// Execute business logic
processBusinessLogic(userId);
// Success response
logger_.logHttpRequest("POST", endpoint, 200,
getDuration(start), userId);
} catch (const std::exception& e) {
logger_.logHttpRequest("POST", endpoint, 500,
getDuration(start), userId);
StructuredLogger::LogEntry errorEntry;
errorEntry.operation = "error";
errorEntry.userId = userId;
errorEntry.resource = endpoint;
errorEntry.metadata["error_message"] = e.what();
logger_.logOperation(errorEntry, logging::trivial::error);
}
}
private:
bool authenticateUser(const std::string& userId) {
PerformanceLogger perf(logger_, "user_authentication", userId);
auto start = std::chrono::high_resolution_clock::now();
// Authentication process simulation
std::this_thread::sleep_for(std::chrono::milliseconds(50));
bool success = !userId.empty();
logger_.logDatabaseQuery("SELECT * FROM users WHERE id = ?",
getDuration(start), success);
return success;
}
void processBusinessLogic(const std::string& userId) {
logger_.logBusinessEvent("user_action", userId, {
{"action_type", "data_access"},
{"resource", "user_profile"},
{"method", "GET"}
});
// Process simulation
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
long getDuration(std::chrono::high_resolution_clock::time_point start) {
auto end = std::chrono::high_resolution_clock::now();
return std::chrono::duration_cast<std::chrono::milliseconds>(
end - start).count();
}
};
int main() {
try {
WebService service;
// Simulate multiple requests
service.handleUserRequest("user123", "/api/profile");
service.handleUserRequest("", "/api/profile"); // Authentication failure
service.handleUserRequest("user456", "/api/settings");
} catch (const std::exception& e) {
std::cerr << "Service error: " << e.what() << std::endl;
return 1;
}
return 0;
}
Asynchronous Logging and Performance Optimization
#include <boost/log/sinks/async_frontend.hpp>
#include <boost/log/sinks/unbounded_fifo_queue.hpp>
#include <boost/log/attributes/scoped_attribute.hpp>
#include <boost/thread/thread.hpp>
#include <atomic>
namespace logging = boost::log;
namespace sinks = boost::log::sinks;
// High-performance asynchronous logger
class HighPerformanceLogger {
public:
typedef sinks::asynchronous_sink<
sinks::text_file_backend,
sinks::unbounded_fifo_queue
> async_file_sink;
static void initialize() {
// Asynchronous file sink setup
auto backend = boost::make_shared<sinks::text_file_backend>(
keywords::file_name = "high_perf_%N.log",
keywords::rotation_size = 100 * 1024 * 1024, // 100MB
keywords::time_based_rotation =
sinks::file::rotation_at_time_point(0, 0, 0)
);
auto asyncSink = boost::make_shared<async_file_sink>(backend);
// Format setup
asyncSink->set_formatter(
expr::format("[%1%] [%2%] [%3%] %4%")
% expr::format_date_time<boost::posix_time::ptime>(
"TimeStamp", "%Y-%m-%d %H:%M:%S.%f")
% expr::attr<std::string>("Channel")
% logging::trivial::severity
% expr::smessage
);
// Filter setup
asyncSink->set_filter(
logging::trivial::severity >= logging::trivial::debug
);
logging::core::get()->add_sink(asyncSink);
// Dedicated console sink (synchronous)
auto consoleSink = logging::add_console_log(
std::cout,
keywords::format = "[%TimeStamp%] [%Severity%] %Message%"
);
consoleSink->set_filter(
logging::trivial::severity >= logging::trivial::info
);
logging::add_common_attributes();
}
// Batch processing logger
static void logBatch(const std::vector<std::string>& messages,
logging::trivial::severity_level level = logging::trivial::info) {
for (const auto& msg : messages) {
BOOST_LOG_TRIVIAL_LEVEL(level) << msg;
}
}
// Metrics collection
static void logMetrics(const std::map<std::string, double>& metrics) {
BOOST_LOG_SCOPED_ATTRIBUTE("Channel", attrs::constant<std::string>("Metrics"));
for (const auto& metric : metrics) {
BOOST_LOG_TRIVIAL(info) << metric.first << "=" << metric.second;
}
}
};
// Worker thread logger
class WorkerLogger {
private:
std::atomic<bool> running_{true};
std::queue<std::string> messageQueue_;
std::mutex queueMutex_;
std::condition_variable queueCondition_;
std::thread workerThread_;
public:
WorkerLogger() {
workerThread_ = std::thread([this]() { processMessages(); });
}
~WorkerLogger() {
stop();
}
void enqueueMessage(const std::string& message,
logging::trivial::severity_level level = logging::trivial::info) {
{
std::lock_guard<std::mutex> lock(queueMutex_);
messageQueue_.push(formatMessage(message, level));
}
queueCondition_.notify_one();
}
void stop() {
if (running_.exchange(false)) {
queueCondition_.notify_all();
if (workerThread_.joinable()) {
workerThread_.join();
}
}
}
private:
void processMessages() {
while (running_ || !messageQueue_.empty()) {
std::unique_lock<std::mutex> lock(queueMutex_);
queueCondition_.wait(lock, [this]() {
return !messageQueue_.empty() || !running_;
});
while (!messageQueue_.empty()) {
auto message = messageQueue_.front();
messageQueue_.pop();
lock.unlock();
// Message processing (actual log output)
BOOST_LOG_TRIVIAL(info) << message;
lock.lock();
}
}
}
std::string formatMessage(const std::string& message,
logging::trivial::severity_level level) {
auto now = boost::posix_time::microsec_clock::local_time();
std::ostringstream oss;
oss << "[WORKER] " << boost::posix_time::to_simple_string(now)
<< " [" << level << "] " << message;
return oss.str();
}
};
// Benchmark class
class LoggingBenchmark {
private:
std::chrono::high_resolution_clock::time_point start_;
std::string testName_;
std::atomic<long> messageCount_{0};
public:
LoggingBenchmark(const std::string& testName) : testName_(testName) {
start_ = std::chrono::high_resolution_clock::now();
BOOST_LOG_TRIVIAL(info) << "Benchmark started: " << testName_;
}
~LoggingBenchmark() {
auto end = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(
end - start_).count();
long totalMessages = messageCount_.load();
double messagesPerSecond = totalMessages * 1000.0 / duration;
BOOST_LOG_TRIVIAL(info) << "Benchmark completed: " << testName_
<< " - " << totalMessages << " messages in "
<< duration << "ms ("
<< std::fixed << std::setprecision(2)
<< messagesPerSecond << " msgs/sec)";
}
void incrementMessageCount() {
messageCount_++;
}
// Synchronous log test
void testSyncLogging(int messageCount) {
for (int i = 0; i < messageCount; ++i) {
BOOST_LOG_TRIVIAL(debug) << "Sync message " << i;
incrementMessageCount();
}
}
// Asynchronous log test
void testAsyncLogging(int messageCount) {
for (int i = 0; i < messageCount; ++i) {
BOOST_LOG_TRIVIAL(debug) << "Async message " << i;
incrementMessageCount();
}
}
// Multi-thread test
void testMultiThreadLogging(int threadCount, int messagesPerThread) {
std::vector<std::thread> threads;
for (int t = 0; t < threadCount; ++t) {
threads.emplace_back([this, t, messagesPerThread]() {
for (int i = 0; i < messagesPerThread; ++i) {
BOOST_LOG_TRIVIAL(debug)
<< "Thread " << t << " message " << i;
incrementMessageCount();
}
});
}
for (auto& thread : threads) {
thread.join();
}
}
};
// Usage example and performance test
int main() {
try {
// High-performance logger initialization
HighPerformanceLogger::initialize();
// Basic performance test
{
LoggingBenchmark benchmark("Sync log 10,000 messages");
benchmark.testSyncLogging(10000);
}
// Multi-thread test
{
LoggingBenchmark benchmark("Multi-thread 5 threads x 2,000 messages");
benchmark.testMultiThreadLogging(5, 2000);
}
// Worker log test
{
LoggingBenchmark benchmark("Worker log 5,000 messages");
WorkerLogger workerLogger;
for (int i = 0; i < 5000; ++i) {
workerLogger.enqueueMessage("Worker message " + std::to_string(i));
benchmark.incrementMessageCount();
}
// Wait for worker completion
std::this_thread::sleep_for(std::chrono::seconds(1));
}
// Metrics collection example
std::map<std::string, double> performanceMetrics = {
{"cpu_usage", 45.7},
{"memory_usage", 234.8},
{"response_time_avg", 125.5},
{"requests_per_second", 1250.0}
};
HighPerformanceLogger::logMetrics(performanceMetrics);
BOOST_LOG_TRIVIAL(info) << "All benchmarks completed";
} catch (const std::exception& e) {
std::cerr << "Benchmark error: " << e.what() << std::endl;
return 1;
}
return 0;
}