The Asio (http://think-async.com) Official example gives a relatively preliminary log service, with the main code in BASIC_LOGGER.HPP, LOGGER_SERVICE.HPP, Logger_ Service.cpp these 3 files. Improvements (such as creating a separate directory for log files, formatting log file names, and each line of logs, creating new log files on a regular basis) can build a usable log system.
A new logger class is inherited from Basic_logger<logger_service>, and a timer and timed event are created in logger, and a log file is regenerated every time a specified period is made.
Make a slight modification to the Use_file method in the Basic_logger class, where you create the directory where the log file is stored and respond to the request to generate a new log file, which can be distinguished by using the build time name.
//basic_logger.hpp void use_file (const std::string& file) {
Create new dir for log files //Create new log file ' s name depends on time
... ... Service_.use_file (impl_, file); } void log (const std::string& message) { Service_.log (Impl_, message); }
As can be seen from the BASIC_LOGGER.HPP code, the real IO operation, whether it is the creation of a log file or the write of a log record, is performed in Logger_service. When writing to log, it is advisable to add a time prefix for future log analysis.
//logger_service.hpp voidUse_file (impl_type&/*Impl*/,ConstSTD::string&file) {Work_io_service_.post (Boost::bind (&logger_service::use_file_impl, This, file)); } voidLog (impl_type& Impl,ConstSTD::string&message) { //Add time prefixStd::ostringstream os; OS<< ... <<": "<<message; Work_io_service_.post (Boost::bind (&logger_service::log_impl, This, Os.str ())); } voidUse_file_impl (ConstSTD::string&file) {Ofstream_.close (); Ofstream_.clear (); Ofstream_.open (File.c_str ()); } voidLog_impl (ConstSTD::string&text) {OFSTREAM_<< text <<Std::endl; }
In Logger_service, both Use_file and log call the Post method to put the callback into the event queue of the internal IO object. Use_file_impl is responsible for creating a new log file, Log_impl is responsible for writing the log file, and all callback functions are called within a single thread, so that even if they share ofstream_, no lock protection is required.
Test performance on a virtual machine, CentOS 6.5, single core, 1G memory, write 1 million logs in 15 seconds.
Using ASIO to build a log system