00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011 #ifndef SERVICES_LOGGER_SERVICE_HPP
00012 #define SERVICES_LOGGER_SERVICE_HPP
00013
00014 #include <asio.hpp>
00015 #include <boost/bind.hpp>
00016 #include <boost/date_time/posix_time/posix_time.hpp>
00017 #include <boost/noncopyable.hpp>
00018 #include <boost/scoped_ptr.hpp>
00019 #include <fstream>
00020 #include <sstream>
00021 #include <string>
00022
00023 namespace services {
00024
00026 class logger_service
00027 : public asio::io_service::service
00028 {
00029 public:
00031 static asio::io_service::id id;
00032
00034 struct logger_impl
00035 {
00036 explicit logger_impl(const std::string& id) : identifier(id) {}
00037 std::string identifier;
00038 };
00039
00041 typedef logger_impl* impl_type;
00042
00044 logger_service(asio::io_service& io_service)
00045 : asio::io_service::service(io_service),
00046 work_io_service_(),
00047 work_(new asio::io_service::work(work_io_service_)),
00048 work_thread_(new asio::thread(
00049 boost::bind(&asio::io_service::run, &work_io_service_)))
00050 {
00051 }
00052
00054 ~logger_service()
00055 {
00058 work_.reset();
00059 if (work_thread_)
00060 work_thread_->join();
00061 }
00062
00064 void shutdown_service()
00065 {
00066 }
00067
00069 impl_type null() const
00070 {
00071 return 0;
00072 }
00073
00075 void create(impl_type& impl, const std::string& identifier)
00076 {
00077 impl = new logger_impl(identifier);
00078 }
00079
00081 void destroy(impl_type& impl)
00082 {
00083 delete impl;
00084 impl = null();
00085 }
00086
00091 void use_file(impl_type& impl, const std::string& file)
00092 {
00093
00094 work_io_service_.post(boost::bind(
00095 &logger_service::use_file_impl, this, file));
00096 }
00097
00099 void log(impl_type& impl, const std::string& message)
00100 {
00101
00102 std::ostringstream os;
00103 os << impl->identifier << ": " << message;
00104
00105
00106 work_io_service_.post(boost::bind(
00107 &logger_service::log_impl, this, os.str()));
00108 }
00109
00110 private:
00113 void use_file_impl(const std::string& file)
00114 {
00115 ofstream_.close();
00116 ofstream_.clear();
00117 ofstream_.open(file.c_str());
00118 }
00119
00122 void log_impl(const std::string& text)
00123 {
00124 ofstream_ << text << std::endl;
00125 }
00126
00128 asio::io_service work_io_service_;
00129
00133 boost::scoped_ptr<asio::io_service::work> work_;
00134
00136 boost::scoped_ptr<asio::thread> work_thread_;
00137
00139 std::ofstream ofstream_;
00140 };
00141
00142 }
00143
00144 #endif // SERVICES_LOGGER_SERVICE_HPP