format.hpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. //
  2. // format.hpp
  3. // logger
  4. //
  5. // Created by Sam Jaffe on 8/21/16.
  6. //
  7. #pragma once
  8. #include <functional>
  9. #include <sstream>
  10. #include <string>
  11. #include <vector>
  12. #include "logger_fwd.hpp"
  13. namespace logging {
  14. class format {
  15. public:
  16. enum class token_id {
  17. DATE, PRIORITY, CATEGORY, MESSAGE, STRING, NEWLINE
  18. };
  19. using generator = std::function<void(logpacket const &, std::ostream &)>;
  20. private:
  21. static format parse_format_string(std::string const &);
  22. std::vector<generator> gen;
  23. };
  24. inline void format_msg( std::stringstream & msg,
  25. std::string const & interp, size_t pos) {
  26. msg << interp.substr(pos);
  27. }
  28. struct format_point_t {
  29. size_t start;
  30. size_t end;
  31. };
  32. format_point_t get_next_format_specifier( std::string const & interp, size_t pos );
  33. template <typename Arg0, typename... Args>
  34. inline void format_msg( std::stringstream & msg,
  35. std::string const & interp, size_t pos,
  36. Arg0 && arg0, Args && ...args ) {
  37. format_point_t next = get_next_format_specifier( interp, pos );
  38. msg << interp.substr(pos, next.start) << arg0;
  39. if ( next.start == std::string::npos ) return; // throw?
  40. format_msg( msg, interp, next.end,
  41. std::forward<Args>(args)... );
  42. }
  43. template <typename... Args>
  44. inline std::string format_msg( std::string const & interp,
  45. Args && ...args ) {
  46. std::stringstream msg;
  47. format_msg<Args...>( msg, interp, 0, std::forward<Args>(args)... );
  48. return msg.str();
  49. }
  50. }