2 * Copyright Andrey Semashev 2007 - 2014.
3 * Distributed under the Boost Software License, Version 1.0.
4 * (See accompanying file LICENSE_1_0.txt or copy at
5 * http://www.boost.org/LICENSE_1_0.txt)
9 * \author Andrey Semashev
12 * \brief An example of logging into a rotating text file.
13 * See the library tutorial for expanded comments on this code.
14 * It may also be worthwhile reading the Wiki requirements page:
15 * http://www.crystalclearsoftware.com/cgi-bin/boost_wiki/wiki.pl?Boost.Logging
18 // #define BOOST_LOG_DYN_LINK 1
23 #include <boost/smart_ptr/shared_ptr.hpp>
24 #include <boost/date_time/posix_time/posix_time.hpp>
26 #include <boost/log/common.hpp>
27 #include <boost/log/expressions.hpp>
28 #include <boost/log/attributes.hpp>
29 #include <boost/log/sources/logger.hpp>
30 #include <boost/log/sinks/sync_frontend.hpp>
31 #include <boost/log/sinks/text_file_backend.hpp>
33 namespace logging = boost::log;
34 namespace attrs = boost::log::attributes;
35 namespace src = boost::log::sources;
36 namespace sinks = boost::log::sinks;
37 namespace expr = boost::log::expressions;
38 namespace keywords = boost::log::keywords;
40 using boost::shared_ptr;
42 enum { LOG_RECORDS_TO_WRITE = 10000 };
44 int main(int argc, char* argv[])
48 // Create a text file sink
49 typedef sinks::synchronous_sink< sinks::text_file_backend > file_sink;
50 shared_ptr< file_sink > sink(new file_sink(
51 keywords::file_name = "%Y%m%d_%H%M%S_%5N.log", // file name pattern
52 keywords::rotation_size = 16384 // rotation size, in characters
55 // Set up where the rotated files will be stored
56 sink->locked_backend()->set_file_collector(sinks::file::make_collector(
57 keywords::target = "logs", // where to store rotated files
58 keywords::max_size = 16 * 1024 * 1024, // maximum total size of the stored files, in bytes
59 keywords::min_free_space = 100 * 1024 * 1024 // minimum free space on the drive, in bytes
62 // Upon restart, scan the target directory for files matching the file_name pattern
63 sink->locked_backend()->scan_for_files();
67 expr::format("%1%: [%2%] - %3%")
68 % expr::attr< unsigned int >("RecordID")
69 % expr::attr< boost::posix_time::ptime >("TimeStamp")
74 logging::core::get()->add_sink(sink);
76 // Add some attributes too
77 logging::core::get()->add_global_attribute("TimeStamp", attrs::local_clock());
78 logging::core::get()->add_global_attribute("RecordID", attrs::counter< unsigned int >());
82 for (unsigned int i = 0; i < LOG_RECORDS_TO_WRITE; ++i)
84 BOOST_LOG(lg) << "Some log record";
89 catch (std::exception& e)
91 std::cout << "FAILURE: " << e.what() << std::endl;