00001 #ifndef SERVICES_LOGGER_SERVICE_HPP
00002 #define SERVICES_LOGGER_SERVICE_HPP
00003
00004 #include <boost/asio.hpp>
00005 #include <boost/thread.hpp>
00006 #include <boost/bind.hpp>
00007 #include <boost/date_time/posix_time/posix_time.hpp>
00008 #include <boost/noncopyable.hpp>
00009 #include <boost/scoped_ptr.hpp>
00010 #include <fstream>
00011 #include <sstream>
00012 #include <string>
00013
00014 namespace services {
00015
00017 class logger_service
00018 : public boost::asio::io_service::service
00019 {
00020 public:
00022 struct logger_impl
00023 {
00024 explicit logger_impl(const std::string& id) : identifier(id) {}
00025 std::string identifier;
00026 };
00027
00029 typedef logger_impl* impl_type;
00030
00032 logger_service(boost::asio::io_service& io_service)
00033 : boost::asio::io_service::service(io_service),
00034 work_io_service_(),
00035 work_(new boost::asio::io_service::work(work_io_service_)),
00036 work_thread_(new boost::thread(
00037 boost::bind(&boost::asio::io_service::run, &work_io_service_)))
00038 {
00039 }
00040
00042 ~logger_service()
00043 {
00046 work_.reset();
00047 if (work_thread_)
00048 work_thread_->join();
00049 }
00050
00052 void shutdown_service()
00053 {
00054 }
00055
00057 impl_type null() const
00058 {
00059 return 0;
00060 }
00061
00063 void create(impl_type& impl, const std::string& identifier)
00064 {
00065 impl = new logger_impl(identifier);
00066 }
00067
00069 void destroy(impl_type& impl)
00070 {
00071 delete impl;
00072 impl = null();
00073 }
00074
00079 void use_file(impl_type& impl, const std::string& file)
00080 {
00081
00082 work_io_service_.post(boost::bind(
00083 &logger_service::use_file_impl, this, file));
00084 }
00085
00087 void log(impl_type& impl, const std::string& message)
00088 {
00089
00090 std::ostringstream os;
00091 os << boost::posix_time::microsec_clock::universal_time();
00092 os << " - " << impl->identifier << " - " << message;
00093
00094
00095 work_io_service_.post(boost::bind(
00096 &logger_service::log_impl, this, os.str()));
00097 }
00098
00099 private:
00102 void use_file_impl(const std::string& file)
00103 {
00104 ofstream_.close();
00105 ofstream_.clear();
00106 ofstream_.open(file.c_str());
00107 }
00108
00111 void log_impl(const std::string& text)
00112 {
00113 ofstream_ << text << std::endl;
00114 }
00115
00117 boost::asio::io_service work_io_service_;
00118
00122 boost::scoped_ptr<boost::asio::io_service::work> work_;
00123
00125 boost::scoped_ptr<boost::thread> work_thread_;
00126
00128 std::ofstream ofstream_;
00129 };
00130
00131 }
00132
00133 #endif // SERVICES_LOGGER_SERVICE_HPP