tutorial_fmt_format.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. * Copyright Andrey Semashev 2007 - 2015.
  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)
  6. */
  7. #include <fstream>
  8. #include <boost/smart_ptr/shared_ptr.hpp>
  9. #include <boost/smart_ptr/make_shared_object.hpp>
  10. #include <boost/log/core.hpp>
  11. #include <boost/log/trivial.hpp>
  12. #include <boost/log/expressions.hpp>
  13. #include <boost/log/sinks/sync_frontend.hpp>
  14. #include <boost/log/sinks/text_ostream_backend.hpp>
  15. #include <boost/log/sources/severity_logger.hpp>
  16. #include <boost/log/sources/record_ostream.hpp>
  17. #include <boost/log/utility/setup/common_attributes.hpp>
  18. namespace logging = boost::log;
  19. namespace src = boost::log::sources;
  20. namespace expr = boost::log::expressions;
  21. namespace sinks = boost::log::sinks;
  22. namespace keywords = boost::log::keywords;
  23. //[ example_tutorial_formatters_format
  24. void init()
  25. {
  26. typedef sinks::synchronous_sink< sinks::text_ostream_backend > text_sink;
  27. boost::shared_ptr< text_sink > sink = boost::make_shared< text_sink >();
  28. sink->locked_backend()->add_stream(
  29. boost::make_shared< std::ofstream >("sample.log"));
  30. // This makes the sink to write log records that look like this:
  31. // 1: <normal> A normal severity message
  32. // 2: <error> An error severity message
  33. sink->set_formatter
  34. (
  35. expr::format("%1%: <%2%> %3%")
  36. % expr::attr< unsigned int >("LineID")
  37. % logging::trivial::severity
  38. % expr::smessage
  39. );
  40. logging::core::get()->add_sink(sink);
  41. }
  42. //]
  43. int main(int, char*[])
  44. {
  45. init();
  46. logging::add_common_attributes();
  47. using namespace logging::trivial;
  48. src::severity_logger< severity_level > lg;
  49. BOOST_LOG_SEV(lg, trace) << "A trace severity message";
  50. BOOST_LOG_SEV(lg, debug) << "A debug severity message";
  51. BOOST_LOG_SEV(lg, info) << "An informational severity message";
  52. BOOST_LOG_SEV(lg, warning) << "A warning severity message";
  53. BOOST_LOG_SEV(lg, error) << "An error severity message";
  54. BOOST_LOG_SEV(lg, fatal) << "A fatal severity message";
  55. return 0;
  56. }