c_logger.h 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. //
  2. // c_logger.hpp
  3. // logging
  4. //
  5. // Created by Sam Jaffe on 4/1/19.
  6. //
  7. #pragma once
  8. #include <cstdarg>
  9. #include <cstdlib>
  10. #include <cstring>
  11. #include <memory>
  12. #include <string>
  13. #include "level.h"
  14. #define VA_LOGN(level, size) \
  15. do { \
  16. va_list vargs; \
  17. va_start(vargs, fmt); \
  18. vlognf(level, size, fmt, vargs); \
  19. va_end(vargs); \
  20. } while (0)
  21. #define VA_LOG(level) VA_LOGN(level, c_logger::LOGF_MAX_SIZE)
  22. #define MAKE_LOGGER_FMT(lvl) \
  23. inline void lvl##f(char const * fmt, ...) { VA_LOG(level::lvl); } \
  24. inline void lvl##nf(size_t n, char const * fmt, ...) { \
  25. VA_LOGN(level::lvl, n); \
  26. } \
  27. inline void lvl(char const * msg) { log(level::lvl, msg); } \
  28. inline void lvl(std::string const & msg) { log(level::lvl, msg); }
  29. namespace logging {
  30. enum class level : int;
  31. class logger_impl;
  32. /**
  33. * A simple logger interface that is used for performing C-Style logging a la
  34. * printf()/nprintf().
  35. * TODO: Add the option to provide location_info with the log_here macro
  36. * Unlink the logging::logger class, this class only provides access to its
  37. * logging methods through functions like warn(), error(), fatal(), etc.
  38. * Each of these functions corresponds to a logging::level enum, and
  39. * constructs its message by calling vsnprintf() under the hood.
  40. * Overrides for no formatting, std::string inputs, and explicitly sizing the
  41. * storage buffer are made available with the following function names e.g.:
  42. * error("This is a string") -> logs "This is a string"
  43. * error(std::string("This is a string")) -> logs "This is a string"
  44. * errorf("This is a %s", "string") -> logs "This is a string"
  45. * errornf(14, "This is a %s", "string") -> logs "This is a str"
  46. */
  47. class c_logger {
  48. private:
  49. friend class manager;
  50. std::string logger_name_;
  51. std::shared_ptr<logger_impl> impl_;
  52. public:
  53. static const size_t LOGF_MAX_SIZE = 2048;
  54. public:
  55. MAKE_LOGGER_FMT(trace)
  56. MAKE_LOGGER_FMT(debug)
  57. MAKE_LOGGER_FMT(info)
  58. MAKE_LOGGER_FMT(warn)
  59. MAKE_LOGGER_FMT(error)
  60. MAKE_LOGGER_FMT(critical)
  61. MAKE_LOGGER_FMT(fatal)
  62. void flush();
  63. ~c_logger();
  64. protected:
  65. c_logger(std::string const & name, std::shared_ptr<logger_impl> impl);
  66. private:
  67. void vlognf(level, size_t, char const *, va_list);
  68. void log(level, std::string const &);
  69. };
  70. }
  71. #undef VA_LOG
  72. #undef LA_LOGN