sinks_unlocked.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 <iostream>
  9. #include <boost/smart_ptr/shared_ptr.hpp>
  10. #include <boost/log/core.hpp>
  11. #include <boost/log/expressions.hpp>
  12. #include <boost/log/sinks/unlocked_frontend.hpp>
  13. #include <boost/log/sinks/basic_sink_backend.hpp>
  14. #include <boost/log/sinks/frontend_requirements.hpp>
  15. #include <boost/log/sources/severity_channel_logger.hpp>
  16. #include <boost/log/sources/record_ostream.hpp>
  17. namespace logging = boost::log;
  18. namespace src = boost::log::sources;
  19. namespace expr = boost::log::expressions;
  20. namespace sinks = boost::log::sinks;
  21. namespace keywords = boost::log::keywords;
  22. //[ example_sinks_unlocked
  23. enum severity_level
  24. {
  25. normal,
  26. warning,
  27. error
  28. };
  29. // A trivial sink backend that requires no thread synchronization
  30. class my_backend :
  31. public sinks::basic_sink_backend< sinks::concurrent_feeding >
  32. {
  33. public:
  34. // The function is called for every log record to be written to log
  35. void consume(logging::record_view const& rec)
  36. {
  37. // We skip the actual synchronization code for brevity
  38. std::cout << rec[expr::smessage] << std::endl;
  39. }
  40. };
  41. // Complete sink type
  42. typedef sinks::unlocked_sink< my_backend > sink_t;
  43. void init_logging()
  44. {
  45. boost::shared_ptr< logging::core > core = logging::core::get();
  46. // The simplest way, the backend is default-constructed
  47. boost::shared_ptr< sink_t > sink1(new sink_t());
  48. core->add_sink(sink1);
  49. // One can construct backend separately and pass it to the frontend
  50. boost::shared_ptr< my_backend > backend(new my_backend());
  51. boost::shared_ptr< sink_t > sink2(new sink_t(backend));
  52. core->add_sink(sink2);
  53. // You can manage filtering through the sink interface
  54. sink1->set_filter(expr::attr< severity_level >("Severity") >= warning);
  55. sink2->set_filter(expr::attr< std::string >("Channel") == "net");
  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, normal) << "Hello world!";
  63. return 0;
  64. }