標準出力とファイルにログを出力したい
Iostreamsのtee_deviceを使って2つのデバイスに出力することにしました。
#include <iostream> #include <boost/iostreams/filtering_stream.hpp> #include <boost/iostreams/device/file.hpp> #include <boost/iostreams/tee.hpp> #include <boost/date_time/posix_time/posix_time.hpp> namespace myns{ namespace io = boost::iostreams; io::filtering_ostream out( io::tee_device<std::ostream, io::file_sink>( std::cout, io::file_sink("log.txt", std::ios::out | std::ios::app) )); } #define LOG(x) myns::out \ << boost::posix_time::second_clock::local_time() \ << " " << x << std::endl int main(){ //サンプルのため変数や処理は適当 bool uploaded = true; int heart_rate = 65535; bool breathed_deeply = false; //... if(!uploaded){ return 1; } LOG("昔の絵をアップロード完了"); //... if(heart_rate >= 1000){ LOG("緊張により心拍数 1000/m オーバー" << " (" << heart_rate << "/m)"); } //... if(!breathed_deeply){ LOG("深呼吸に失敗"); return 1; } //... return 0; }
標準出力, ファイル "log.txt":
2012-Jul-25 23:14:24 昔の絵をアップロード完了 2012-Jul-25 23:14:24 緊張により心拍数 1000/m オーバー (65535/m) 2012-Jul-25 23:14:24 深呼吸に失敗