format.h 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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.h"
  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, std::string const & interp,
  25. 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,
  33. size_t pos );
  34. template <typename Arg0, typename... Args>
  35. inline void format_msg(std::stringstream & msg, std::string const & interp,
  36. size_t pos, Arg0 && arg0, Args && ...args) {
  37. format_point_t next = get_next_format_specifier( interp, pos );
  38. msg << interp.substr(pos, next.start);
  39. if (next.start == std::string::npos) {
  40. return; // throw?
  41. } else if (!strncmp(interp.c_str() + next.start - 1, "{{}}", 4)) {
  42. format_msg(msg, interp, next.end, std::forward<Arg0>(arg0),
  43. std::forward<Args>(args)... );
  44. } else {
  45. msg << arg0;
  46. format_msg(msg, interp, next.end, std::forward<Args>(args)... );
  47. }
  48. }
  49. template <typename... Args>
  50. inline std::string format_msg(std::string const & interp,
  51. Args && ...args) {
  52. std::stringstream msg;
  53. format_msg<Args...>( msg, interp, 0, std::forward<Args>(args)... );
  54. return msg.str();
  55. }
  56. }