format.h 1.7 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.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. static format parse_format_string(std::string const &);
  21. void process(logpacket const & pkt, std::ostream & os) const;
  22. std::string process(logpacket const & pkt) const;
  23. private:
  24. std::vector<generator> gen;
  25. };
  26. inline void format_msg(std::stringstream & msg, std::string const & interp,
  27. size_t pos) {
  28. msg << interp.substr(pos);
  29. }
  30. template <typename Arg0, typename... Args>
  31. inline void format_msg(std::stringstream & msg, std::string const & interp,
  32. size_t pos, Arg0 && arg0, Args && ...args) {
  33. size_t next = interp.find("{}", pos);
  34. msg << interp.substr(pos, next);
  35. if (next == std::string::npos) {
  36. return; // throw?
  37. } else if (!strncmp(interp.c_str() + next - 1, "{{}}", 4)) {
  38. format_msg(msg, interp, next+2, std::forward<Arg0>(arg0),
  39. std::forward<Args>(args)... );
  40. } else {
  41. msg << arg0;
  42. format_msg(msg, interp, next+2, std::forward<Args>(args)... );
  43. }
  44. }
  45. template <typename... Args>
  46. inline std::string format_msg(std::string const & interp,
  47. Args && ...args) {
  48. std::stringstream msg;
  49. format_msg<Args...>( msg, interp, 0, std::forward<Args>(args)... );
  50. return msg.str();
  51. }
  52. }