sinks_sync.cpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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 <string>
  8. #include <fstream>
  9. #include <iostream>
  10. #include <boost/smart_ptr/shared_ptr.hpp>
  11. #include <boost/core/null_deleter.hpp>
  12. #include <boost/log/core.hpp>
  13. #include <boost/log/expressions.hpp>
  14. #include <boost/log/sinks/sync_frontend.hpp>
  15. #include <boost/log/sinks/text_ostream_backend.hpp>
  16. #include <boost/log/sources/severity_channel_logger.hpp>
  17. #include <boost/log/sources/record_ostream.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_sinks_sync
  24. enum severity_level
  25. {
  26. normal,
  27. warning,
  28. error
  29. };
  30. // Complete sink type
  31. typedef sinks::synchronous_sink< sinks::text_ostream_backend > sink_t;
  32. void init_logging()
  33. {
  34. boost::shared_ptr< logging::core > core = logging::core::get();
  35. // Create a backend and initialize it with a stream
  36. boost::shared_ptr< sinks::text_ostream_backend > backend =
  37. boost::make_shared< sinks::text_ostream_backend >();
  38. backend->add_stream(
  39. boost::shared_ptr< std::ostream >(&std::clog, boost::null_deleter()));
  40. // Wrap it into the frontend and register in the core
  41. boost::shared_ptr< sink_t > sink(new sink_t(backend));
  42. core->add_sink(sink);
  43. // You can manage filtering and formatting through the sink interface
  44. sink->set_filter(expr::attr< severity_level >("Severity") >= warning);
  45. sink->set_formatter
  46. (
  47. expr::stream
  48. << "Level: " << expr::attr< severity_level >("Severity")
  49. << " Message: " << expr::smessage
  50. );
  51. // You can also manage backend in a thread-safe manner
  52. {
  53. sink_t::locked_backend_ptr p = sink->locked_backend();
  54. p->add_stream(boost::make_shared< std::ofstream >("sample.log"));
  55. } // the backend gets released here
  56. }
  57. //]
  58. int main(int, char*[])
  59. {
  60. init_logging();
  61. src::severity_channel_logger< severity_level > lg(keywords::channel = "net");
  62. BOOST_LOG_SEV(lg, warning) << "Hello world!";
  63. return 0;
  64. }