tutorial_fmt_custom.cpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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 <ostream>
  8. #include <fstream>
  9. #include <boost/smart_ptr/shared_ptr.hpp>
  10. #include <boost/smart_ptr/make_shared_object.hpp>
  11. #include <boost/optional.hpp>
  12. #include <boost/log/core.hpp>
  13. #include <boost/log/trivial.hpp>
  14. #include <boost/log/expressions.hpp>
  15. #include <boost/log/sinks/sync_frontend.hpp>
  16. #include <boost/log/sinks/text_ostream_backend.hpp>
  17. #include <boost/log/sources/severity_logger.hpp>
  18. #include <boost/log/sources/record_ostream.hpp>
  19. #include <boost/log/utility/formatting_ostream.hpp>
  20. #include <boost/log/utility/setup/common_attributes.hpp>
  21. #include <boost/log/attributes/value_extraction.hpp>
  22. namespace logging = boost::log;
  23. namespace src = boost::log::sources;
  24. namespace expr = boost::log::expressions;
  25. namespace sinks = boost::log::sinks;
  26. //[ example_tutorial_formatters_custom
  27. void my_formatter(logging::record_view const& rec, logging::formatting_ostream& strm)
  28. {
  29. // Get the LineID attribute value and put it into the stream
  30. strm << logging::extract< unsigned int >("LineID", rec) << ": ";
  31. // The same for the severity level.
  32. // The simplified syntax is possible if attribute keywords are used.
  33. strm << "<" << rec[logging::trivial::severity] << "> ";
  34. // Finally, put the record message to the stream
  35. strm << rec[expr::smessage];
  36. }
  37. void init()
  38. {
  39. typedef sinks::synchronous_sink< sinks::text_ostream_backend > text_sink;
  40. boost::shared_ptr< text_sink > sink = boost::make_shared< text_sink >();
  41. sink->locked_backend()->add_stream(
  42. boost::make_shared< std::ofstream >("sample.log"));
  43. sink->set_formatter(&my_formatter);
  44. logging::core::get()->add_sink(sink);
  45. }
  46. //]
  47. int main(int, char*[])
  48. {
  49. init();
  50. logging::add_common_attributes();
  51. using namespace logging::trivial;
  52. src::severity_logger< severity_level > lg;
  53. BOOST_LOG_SEV(lg, trace) << "A trace severity message";
  54. BOOST_LOG_SEV(lg, debug) << "A debug severity message";
  55. BOOST_LOG_SEV(lg, info) << "An informational severity message";
  56. BOOST_LOG_SEV(lg, warning) << "A warning severity message";
  57. BOOST_LOG_SEV(lg, error) << "An error severity message";
  58. BOOST_LOG_SEV(lg, fatal) << "A fatal severity message";
  59. return 0;
  60. }