Boost.Log
Boostライブラリ群の一部として提供される包括的なC++ロギングフレームワーク。高度なカスタマイズ性とエンタープライズレベルの機能を提供。複雑な要件に対応できる強力な設定オプションと拡張性を持つ。
ライブラリ
Boost.Log
概要
Boost.Logは、Boostライブラリ群の一部として提供される包括的なC++ロギングフレームワークです。高度なカスタマイズ性とエンタープライズレベルの機能を提供し、複雑な要件に対応できる強力な設定オプションと拡張性を持ちます。複数のログレベル、フィルタリング、フォーマッティング、複数の出力先(ファイル、コンソール、syslog等)への同時書き込みをサポート。マルチスレッド環境での安全性、非同期ログ処理、ログローテーション機能を備え、大規模で複雑なC++プロジェクトでの信頼性の高いロギングソリューションを実現します。
詳細
Boost.Log 2025年版では、大規模で複雑なC++プロジェクトでの選択肢として高い評価を維持し続けています。Boostエコシステムの信頼性と成熟度により、エンタープライズ環境での採用が継続しており、15年以上の開発実績による安定性と後方互換性を提供。設定ファイルベースの柔軟な設定システム、豊富なシンク(出力先)オプション、カスタムフィルターとフォーマッターの実装支援により、企業レベルの要件に対応。CMakeサポートの強化、モダンC++機能の活用、クロスプラットフォーム対応(Windows、Linux、macOS)により現代的な開発環境にも適応しています。
主な特徴
- 包括的なログシステム: 複数のシンク、フィルター、フォーマッターによる高度な制御
- エンタープライズ対応: 設定ファイルベースの管理とプロダクション環境での安定性
- マルチスレッド安全: スレッドセーフなロgging操作と非同期処理サポート
- 豊富な出力先: ファイル、コンソール、syslog、Windowsイベントログ等
- カスタマイズ性: カスタムシンク、フィルター、フォーマッターの実装可能
- Boostエコシステム: 他のBoostライブラリとの統合と一貫した設計
メリット・デメリット
メリット
- Boostライブラリ群の信頼性と15年以上の成熟した開発実績
- エンタープライズレベルの豊富な機能と高度なカスタマイズ性
- 設定ファイルによる実行時設定変更とプロダクション環境での柔軟性
- マルチスレッド環境での安全性と非同期処理による高いパフォーマンス
- 豊富な出力先オプションと複数シンクへの同時出力サポート
- 包括的なドキュメントとコミュニティサポート
デメリット
- 設定の複雑さにより小規模プロジェクトでは過剰仕様
- ヘッダーファイルサイズが大きくコンパイル時間への影響
- 学習コストが高く、シンプルなロギングには不向き
- 依存関係が多く最小限のバイナリサイズを重視する環境には不適
- CMake設定の複雑さと初期セットアップの手間
- モダンなC++向けライブラリと比較して冗長な記述が必要
参考ページ
書き方の例
インストールと基本セットアップ
// Boost.Logのインストール (Ubuntu/Debian)
// sudo apt-get install libboost-log-dev
// Windows (vcpkg)
// vcpkg install boost-log
// CMakeLists.txt設定例
/*
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() {
// 基本的な初期化
logging::add_common_attributes();
// コンソール出力の設定
logging::add_console_log(
std::cout,
keywords::format = "[%TimeStamp%] [%Severity%] %Message%"
);
// 基本的なログ出力
BOOST_LOG_TRIVIAL(trace) << "アプリケーション開始";
BOOST_LOG_TRIVIAL(debug) << "デバッグ情報";
BOOST_LOG_TRIVIAL(info) << "情報メッセージ";
BOOST_LOG_TRIVIAL(warning) << "警告メッセージ";
BOOST_LOG_TRIVIAL(error) << "エラーメッセージ";
BOOST_LOG_TRIVIAL(fatal) << "致命的エラー";
return 0;
}
基本的なログレベルとフィルタリング
#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) {
// グローバルフィルターの設定
logging::core::get()->set_filter(
trivial::severity >= level
);
// コンソール出力設定
logging::add_console_log(
std::cout,
boost::log::keywords::format =
"[%TimeStamp%] [%ThreadID%] [%Severity%] %Message%"
);
// ファイル出力設定
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), // 毎日
boost::log::keywords::format =
"[%TimeStamp%] [%ThreadID%] [%Severity%] %Message%"
);
logging::add_common_attributes();
}
// ログレベル動的変更
static void setLogLevel(trivial::severity_level level) {
logging::core::get()->set_filter(
trivial::severity >= level
);
}
// 統計情報取得
static void logStatistics() {
auto core = logging::core::get();
BOOST_LOG_TRIVIAL(info) << "ログコア設定完了";
}
};
// 使用例
void demonstrateLogLevels() {
// 初期化(INFOレベル以上のみ表示)
LogManager::initialize(trivial::info);
BOOST_LOG_TRIVIAL(trace) << "トレース - 表示されない";
BOOST_LOG_TRIVIAL(debug) << "デバッグ - 表示されない";
BOOST_LOG_TRIVIAL(info) << "情報 - 表示される";
BOOST_LOG_TRIVIAL(warning) << "警告 - 表示される";
BOOST_LOG_TRIVIAL(error) << "エラー - 表示される";
// デバッグレベルに変更
LogManager::setLogLevel(trivial::debug);
BOOST_LOG_TRIVIAL(debug) << "デバッグ - 今度は表示される";
// カスタムメッセージ
BOOST_LOG_TRIVIAL(info) << "ユーザーID: " << 12345 << ", 操作: ログイン成功";
}
// スレッドセーフなロギング例
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)
<< "スレッド " << i << " - メッセージ " << j;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
});
}
for (auto& t : threads) {
t.join();
}
}
int main() {
demonstrateLogLevels();
threadSafeLogging();
return 0;
}
設定ファイルベースの高度な設定
// settings.ini ファイル例
/*
[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);
}
// 設定ファイルからの初期化
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) << "設定ファイル '" << configFile << "' からロギング設定を読み込み完了";
} catch (const std::exception& e) {
std::cerr << "設定ファイル読み込みエラー: " << e.what() << std::endl;
// フォールバック設定
logging::add_console_log(
std::cout,
boost::log::keywords::format = "[%TimeStamp%] [%Severity%] %Message%"
);
logging::add_common_attributes();
}
}
// チャンネル別ログ出力
template<typename T>
void log(logging::trivial::severity_level level, const T& message) {
BOOST_LOG_SEV(logger_, level) << message;
}
// 便利メソッド
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); }
};
// アプリケーションクラス例
class Application {
private:
ConfigurableLogger authLogger_;
ConfigurableLogger dbLogger_;
ConfigurableLogger apiLogger_;
public:
Application()
: authLogger_("Auth")
, dbLogger_("Database")
, apiLogger_("API") {
}
void run() {
authLogger_.info("認証サービス開始");
dbLogger_.info("データベース接続確立");
apiLogger_.info("APIサーバー起動");
// 業務ロジック実行
simulateUserAuthentication();
simulateDatabaseOperations();
simulateAPIRequests();
authLogger_.info("認証サービス終了");
dbLogger_.info("データベース接続切断");
apiLogger_.info("APIサーバー停止");
}
private:
void simulateUserAuthentication() {
authLogger_.debug("ユーザー認証処理開始");
try {
// 認証処理のシミュレーション
authLogger_.info("ユーザー 'user123' ログイン成功");
} catch (const std::exception& e) {
authLogger_.error("認証エラー: " + std::string(e.what()));
}
}
void simulateDatabaseOperations() {
dbLogger_.debug("データベース操作開始");
try {
dbLogger_.info("SELECT クエリ実行: users テーブル");
dbLogger_.info("クエリ実行時間: 25ms");
} catch (const std::exception& e) {
dbLogger_.error("データベースエラー: " + std::string(e.what()));
}
}
void simulateAPIRequests() {
apiLogger_.debug("API リクエスト処理開始");
apiLogger_.info("GET /api/users - 200 OK - 45ms");
apiLogger_.warning("POST /api/users - レート制限警告");
apiLogger_.error("DELETE /api/users/invalid - 404 Not Found");
}
};
int main() {
try {
// 設定ファイルから初期化
ConfigurableLogger::initializeFromFile("settings.ini");
// アプリケーション実行
Application app;
app.run();
} catch (const std::exception& e) {
std::cerr << "アプリケーションエラー: " << e.what() << std::endl;
return 1;
}
return 0;
}
カスタムシンクとフォーマッターの実装
#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;
// カスタムシンクの実装例(JSON形式でファイル出力)
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>();
// ファイルストリーム追加
backend->add_stream(
boost::shared_ptr<std::ostream>(new std::ofstream(fileName))
);
// 自動フラッシュ設定
backend->auto_flush(true);
auto sink = boost::make_shared<sink_t>(backend);
// カスタムJSONフォーマッター設定
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;
}
};
// カスタム構造化ロガーの実装
class StructuredLogger {
private:
src::severity_logger<logging::trivial::severity_level> logger_;
boost::shared_ptr<JsonFileSink::sink_t> jsonSink_;
public:
StructuredLogger() {
setupSinks();
}
// 構造化ログエントリ
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();
}
// 便利メソッド
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形式でのファイル出力
jsonSink_ = JsonFileSink::create("structured_logs.json");
logging::core::get()->add_sink(jsonSink_);
// 標準的なコンソール出力
auto consoleSink = logging::add_console_log(
std::cout,
keywords::format = "[%TimeStamp%] [%Severity%] %Message%"
);
// 共通属性追加
logging::add_common_attributes();
}
};
// パフォーマンス監視付きロガー
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();
// 操作開始ログ
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();
// 操作完了ログ
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);
}
};
// 使用例
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 {
// 認証
if (!authenticateUser(userId)) {
logger_.logHttpRequest("POST", endpoint, 401,
getDuration(start), userId);
return;
}
// ビジネスロジック実行
processBusinessLogic(userId);
// 成功応答
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();
// 認証処理のシミュレーション
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"}
});
// 処理のシミュレーション
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;
// 複数のリクエストをシミュレーション
service.handleUserRequest("user123", "/api/profile");
service.handleUserRequest("", "/api/profile"); // 認証失敗
service.handleUserRequest("user456", "/api/settings");
} catch (const std::exception& e) {
std::cerr << "サービスエラー: " << e.what() << std::endl;
return 1;
}
return 0;
}
非同期ログとパフォーマンス最適化
#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;
// 高性能非同期ロガー
class HighPerformanceLogger {
public:
typedef sinks::asynchronous_sink<
sinks::text_file_backend,
sinks::unbounded_fifo_queue
> async_file_sink;
static void initialize() {
// 非同期ファイルシンクの設定
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);
// フォーマット設定
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
);
// フィルター設定
asyncSink->set_filter(
logging::trivial::severity >= logging::trivial::debug
);
logging::core::get()->add_sink(asyncSink);
// 専用コンソールシンク(同期)
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();
}
// バッチ処理対応ロガー
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;
}
}
// メトリクス収集
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;
}
}
};
// ワーカースレッド用ロガー
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();
// メッセージ処理(実際のログ出力)
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();
}
};
// ベンチマーク用クラス
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) << "ベンチマーク開始: " << 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) << "ベンチマーク完了: " << testName_
<< " - " << totalMessages << " messages in "
<< duration << "ms ("
<< std::fixed << std::setprecision(2)
<< messagesPerSecond << " msgs/sec)";
}
void incrementMessageCount() {
messageCount_++;
}
// 同期ログテスト
void testSyncLogging(int messageCount) {
for (int i = 0; i < messageCount; ++i) {
BOOST_LOG_TRIVIAL(debug) << "同期メッセージ " << i;
incrementMessageCount();
}
}
// 非同期ログテスト
void testAsyncLogging(int messageCount) {
for (int i = 0; i < messageCount; ++i) {
BOOST_LOG_TRIVIAL(debug) << "非同期メッセージ " << i;
incrementMessageCount();
}
}
// マルチスレッドテスト
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)
<< "スレッド " << t << " メッセージ " << i;
incrementMessageCount();
}
});
}
for (auto& thread : threads) {
thread.join();
}
}
};
// 使用例とパフォーマンステスト
int main() {
try {
// 高性能ロガー初期化
HighPerformanceLogger::initialize();
// 基本性能テスト
{
LoggingBenchmark benchmark("同期ログ 10,000 メッセージ");
benchmark.testSyncLogging(10000);
}
// マルチスレッドテスト
{
LoggingBenchmark benchmark("マルチスレッド 5スレッド x 2,000 メッセージ");
benchmark.testMultiThreadLogging(5, 2000);
}
// ワーカーログテスト
{
LoggingBenchmark benchmark("ワーカーログ 5,000 メッセージ");
WorkerLogger workerLogger;
for (int i = 0; i < 5000; ++i) {
workerLogger.enqueueMessage("ワーカーメッセージ " + std::to_string(i));
benchmark.incrementMessageCount();
}
// ワーカー完了待ち
std::this_thread::sleep_for(std::chrono::seconds(1));
}
// メトリクス収集例
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) << "全ベンチマーク完了";
} catch (const std::exception& e) {
std::cerr << "ベンチマークエラー: " << e.what() << std::endl;
return 1;
}
return 0;
}