Log.cc 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Copyright: All Rights Reserved
  2. // Author: egametang@gmail.com (tanghai)
  3. #include <fstream>
  4. #include <iostream>
  5. #include <boost/shared_ptr.hpp>
  6. #include <boost/make_shared.hpp>
  7. #include <boost/date_time/posix_time/posix_time_types.hpp>
  8. #include <boost/log/common.hpp>
  9. #include <boost/log/filters.hpp>
  10. #include <boost/log/formatters.hpp>
  11. #include <boost/log/attributes.hpp>
  12. #include <boost/log/sinks/text_multifile_backend.hpp>
  13. #include <boost/log/attributes/current_thread_id.hpp>
  14. #include "Log/Log.h"
  15. namespace attrs = boost::log::attributes;
  16. namespace fmt = boost::log::formatters;
  17. namespace keywords = boost::log::keywords;
  18. namespace Egametang {
  19. std::string FileName(const char* s)
  20. {
  21. boost::filesystem::path path(s);
  22. return path.filename().string();
  23. }
  24. BoostLogInit::BoostLogInit(const char* fileName)
  25. {
  26. auto core = boost::log::core::get();
  27. core->add_global_attribute("TimeStamp", boost::make_shared<attrs::local_clock>());
  28. core->add_global_attribute("ThreadId", boost::make_shared<attrs::current_thread_id>());
  29. pSink = boost::make_shared<text_sink>();
  30. std::string logFileName = std::string(fileName) + ".log";
  31. auto logStream = boost::make_shared<std::ofstream>(
  32. logFileName.c_str());
  33. if (!logStream->good())
  34. {
  35. throw std::runtime_error("Failed to open a log file");
  36. }
  37. pSink->locked_backend()->add_stream(logStream);
  38. pSink->locked_backend()->auto_flush(true);
  39. pSink->locked_backend()->set_formatter(
  40. fmt::format("%1%: %2% - %3%") % fmt::attr<unsigned int>("LineID", keywords::format =
  41. "%08x")
  42. % fmt::attr<boost::log::attributes::current_thread_id::held_type>("ThreadID")
  43. % fmt::attr<boost::log::trivial::severity_level>("Severity") % fmt::message());
  44. core->add_sink(pSink);
  45. }
  46. BoostLogInit::~BoostLogInit()
  47. {
  48. }
  49. } // Egametang