sinks_multifile.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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/smart_ptr/make_shared_object.hpp>
  11. #include <boost/log/core.hpp>
  12. #include <boost/log/expressions.hpp>
  13. #include <boost/log/sinks/sync_frontend.hpp>
  14. #include <boost/log/sinks/text_multifile_backend.hpp>
  15. #include <boost/log/sources/logger.hpp>
  16. #include <boost/log/sources/record_ostream.hpp>
  17. #include <boost/log/attributes/scoped_attribute.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_multifile
  24. void init_logging()
  25. {
  26. boost::shared_ptr< logging::core > core = logging::core::get();
  27. boost::shared_ptr< sinks::text_multifile_backend > backend =
  28. boost::make_shared< sinks::text_multifile_backend >();
  29. // Set up the file naming pattern
  30. backend->set_file_name_composer
  31. (
  32. sinks::file::as_file_name_composer(expr::stream << "logs/" << expr::attr< std::string >("RequestID") << ".log")
  33. );
  34. // Wrap it into the frontend and register in the core.
  35. // The backend requires synchronization in the frontend.
  36. typedef sinks::synchronous_sink< sinks::text_multifile_backend > sink_t;
  37. boost::shared_ptr< sink_t > sink(new sink_t(backend));
  38. // Set the formatter
  39. sink->set_formatter
  40. (
  41. expr::stream
  42. << "[RequestID: " << expr::attr< std::string >("RequestID")
  43. << "] " << expr::smessage
  44. );
  45. core->add_sink(sink);
  46. }
  47. //]
  48. void logging_function()
  49. {
  50. src::logger lg;
  51. BOOST_LOG(lg) << "Hello, world!";
  52. }
  53. int main(int, char*[])
  54. {
  55. init_logging();
  56. {
  57. BOOST_LOG_SCOPED_THREAD_TAG("RequestID", "Request1");
  58. logging_function();
  59. }
  60. {
  61. BOOST_LOG_SCOPED_THREAD_TAG("RequestID", "Request2");
  62. logging_function();
  63. }
  64. return 0;
  65. }