example.cpp 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. //
  2. // Copyright(c) 2015 Gabi Melman.
  3. // Distributed under the MIT License (http://opensource.org/licenses/MIT)
  4. // spdlog usage example
  5. #include <cstdio>
  6. void load_levels_example();
  7. void stdout_logger_example();
  8. void basic_example();
  9. void rotating_example();
  10. void daily_example();
  11. void async_example();
  12. void binary_example();
  13. void stopwatch_example();
  14. void trace_example();
  15. void multi_sink_example();
  16. void user_defined_example();
  17. void err_handler_example();
  18. void syslog_example();
  19. void custom_flags_example();
  20. #include "spdlog/spdlog.h"
  21. #include "spdlog/cfg/env.h" // for loading levels from the environment variable
  22. int main(int, char *[])
  23. {
  24. // Log levels can be loaded from argv/env using "SPDLOG_LEVEL"
  25. load_levels_example();
  26. spdlog::info("Welcome to spdlog version {}.{}.{} !", SPDLOG_VER_MAJOR, SPDLOG_VER_MINOR, SPDLOG_VER_PATCH);
  27. spdlog::warn("Easy padding in numbers like {:08d}", 12);
  28. spdlog::critical("Support for int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42);
  29. spdlog::info("Support for floats {:03.2f}", 1.23456);
  30. spdlog::info("Positional args are {1} {0}..", "too", "supported");
  31. spdlog::info("{:>8} aligned, {:<8} aligned", "right", "left");
  32. // Runtime log levels
  33. spdlog::set_level(spdlog::level::info); // Set global log level to info
  34. spdlog::debug("This message should not be displayed!");
  35. spdlog::set_level(spdlog::level::trace); // Set specific logger's log level
  36. spdlog::debug("This message should be displayed..");
  37. // Customize msg format for all loggers
  38. spdlog::set_pattern("[%H:%M:%S %z] [%^%L%$] [thread %t] %v");
  39. spdlog::info("This an info message with custom format");
  40. spdlog::set_pattern("%+"); // back to default format
  41. spdlog::set_level(spdlog::level::info);
  42. // Backtrace support
  43. // Loggers can store in a ring buffer all messages (including debug/trace) for later inspection.
  44. // When needed, call dump_backtrace() to see what happened:
  45. spdlog::enable_backtrace(10); // create ring buffer with capacity of 10 messages
  46. for (int i = 0; i < 100; i++)
  47. {
  48. spdlog::debug("Backtrace message {}", i); // not logged..
  49. }
  50. // e.g. if some error happened:
  51. spdlog::dump_backtrace(); // log them now!
  52. try
  53. {
  54. stdout_logger_example();
  55. basic_example();
  56. rotating_example();
  57. daily_example();
  58. async_example();
  59. binary_example();
  60. multi_sink_example();
  61. user_defined_example();
  62. err_handler_example();
  63. trace_example();
  64. stopwatch_example();
  65. custom_flags_example();
  66. // Flush all *registered* loggers using a worker thread every 3 seconds.
  67. // note: registered loggers *must* be thread safe for this to work correctly!
  68. spdlog::flush_every(std::chrono::seconds(3));
  69. // Apply some function on all registered loggers
  70. spdlog::apply_all([&](std::shared_ptr<spdlog::logger> l) { l->info("End of example."); });
  71. // Release all spdlog resources, and drop all loggers in the registry.
  72. // This is optional (only mandatory if using windows + async log).
  73. spdlog::shutdown();
  74. }
  75. // Exceptions will only be thrown upon failed logger or sink construction (not during logging).
  76. catch (const spdlog::spdlog_ex &ex)
  77. {
  78. std::printf("Log initialization failed: %s\n", ex.what());
  79. return 1;
  80. }
  81. }
  82. #include "spdlog/sinks/stdout_color_sinks.h"
  83. // or #include "spdlog/sinks/stdout_sinks.h" if no colors needed.
  84. void stdout_logger_example()
  85. {
  86. // Create color multi threaded logger.
  87. auto console = spdlog::stdout_color_mt("console");
  88. // or for stderr:
  89. // auto console = spdlog::stderr_color_mt("error-logger");
  90. }
  91. #include "spdlog/sinks/basic_file_sink.h"
  92. void basic_example()
  93. {
  94. // Create basic file logger (not rotated).
  95. auto my_logger = spdlog::basic_logger_mt("file_logger", "logs/basic-log.txt");
  96. }
  97. #include "spdlog/sinks/rotating_file_sink.h"
  98. void rotating_example()
  99. {
  100. // Create a file rotating logger with 5mb size max and 3 rotated files.
  101. auto rotating_logger = spdlog::rotating_logger_mt("some_logger_name", "logs/rotating.txt", 1048576 * 5, 3);
  102. }
  103. #include "spdlog/sinks/daily_file_sink.h"
  104. void daily_example()
  105. {
  106. // Create a daily logger - a new file is created every day on 2:30am.
  107. auto daily_logger = spdlog::daily_logger_mt("daily_logger", "logs/daily.txt", 2, 30);
  108. }
  109. #include "spdlog/cfg/env.h"
  110. void load_levels_example()
  111. {
  112. // Set the log level to "info" and mylogger to to "trace":
  113. // SPDLOG_LEVEL=info,mylogger=trace && ./example
  114. spdlog::cfg::load_env_levels();
  115. // or from command line:
  116. // ./example SPDLOG_LEVEL=info,mylogger=trace
  117. // #include "spdlog/cfg/argv.h" // for loading levels from argv
  118. // spdlog::cfg::load_argv_levels(args, argv);
  119. }
  120. #include "spdlog/async.h"
  121. void async_example()
  122. {
  123. // Default thread pool settings can be modified *before* creating the async logger:
  124. // spdlog::init_thread_pool(32768, 1); // queue with max 32k items 1 backing thread.
  125. auto async_file = spdlog::basic_logger_mt<spdlog::async_factory>("async_file_logger", "logs/async_log.txt");
  126. // alternatively:
  127. // auto async_file = spdlog::create_async<spdlog::sinks::basic_file_sink_mt>("async_file_logger", "logs/async_log.txt");
  128. for (int i = 1; i < 101; ++i)
  129. {
  130. async_file->info("Async message #{}", i);
  131. }
  132. }
  133. // Log binary data as hex.
  134. // Many types of std::container<char> types can be used.
  135. // Iterator ranges are supported too.
  136. // Format flags:
  137. // {:X} - print in uppercase.
  138. // {:s} - don't separate each byte with space.
  139. // {:p} - don't print the position on each line start.
  140. // {:n} - don't split the output to lines.
  141. #include "spdlog/fmt/bin_to_hex.h"
  142. void binary_example()
  143. {
  144. std::vector<char> buf(80);
  145. for (int i = 0; i < 80; i++)
  146. {
  147. buf.push_back(static_cast<char>(i & 0xff));
  148. }
  149. spdlog::info("Binary example: {}", spdlog::to_hex(buf));
  150. spdlog::info("Another binary example:{:n}", spdlog::to_hex(std::begin(buf), std::begin(buf) + 10));
  151. // more examples:
  152. // logger->info("uppercase: {:X}", spdlog::to_hex(buf));
  153. // logger->info("uppercase, no delimiters: {:Xs}", spdlog::to_hex(buf));
  154. // logger->info("uppercase, no delimiters, no position info: {:Xsp}", spdlog::to_hex(buf));
  155. // logger->info("hexdump style: {:a}", spdlog::to_hex(buf));
  156. // logger->info("hexdump style, 20 chars per line {:a}", spdlog::to_hex(buf, 20));
  157. }
  158. // Compile time log levels.
  159. // define SPDLOG_ACTIVE_LEVEL to required level (e.g. SPDLOG_LEVEL_TRACE)
  160. void trace_example()
  161. {
  162. // trace from default logger
  163. SPDLOG_TRACE("Some trace message.. {} ,{}", 1, 3.23);
  164. // debug from default logger
  165. SPDLOG_DEBUG("Some debug message.. {} ,{}", 1, 3.23);
  166. // trace from logger object
  167. auto logger = spdlog::get("file_logger");
  168. SPDLOG_LOGGER_TRACE(logger, "another trace message");
  169. }
  170. // stopwatch example
  171. #include "spdlog/stopwatch.h"
  172. #include <thread>
  173. void stopwatch_example()
  174. {
  175. spdlog::stopwatch sw;
  176. std::this_thread::sleep_for(std::chrono::milliseconds(123));
  177. spdlog::info("Stopwatch: {} seconds", sw);
  178. }
  179. // A logger with multiple sinks (stdout and file) - each with a different format and log level.
  180. void multi_sink_example()
  181. {
  182. auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
  183. console_sink->set_level(spdlog::level::warn);
  184. console_sink->set_pattern("[multi_sink_example] [%^%l%$] %v");
  185. auto file_sink = std::make_shared<spdlog::sinks::basic_file_sink_mt>("logs/multisink.txt", true);
  186. file_sink->set_level(spdlog::level::trace);
  187. spdlog::logger logger("multi_sink", {console_sink, file_sink});
  188. logger.set_level(spdlog::level::debug);
  189. logger.warn("this should appear in both console and file");
  190. logger.info("this message should not appear in the console, only in the file");
  191. }
  192. // User defined types logging by implementing operator<<
  193. #include "spdlog/fmt/ostr.h" // must be included
  194. struct my_type
  195. {
  196. int i;
  197. template<typename OStream>
  198. friend OStream &operator<<(OStream &os, const my_type &c)
  199. {
  200. return os << "[my_type i=" << c.i << "]";
  201. }
  202. };
  203. void user_defined_example()
  204. {
  205. spdlog::info("user defined type: {}", my_type{14});
  206. }
  207. // Custom error handler. Will be triggered on log failure.
  208. void err_handler_example()
  209. {
  210. // can be set globally or per logger(logger->set_error_handler(..))
  211. spdlog::set_error_handler([](const std::string &msg) { printf("*** Custom log error handler: %s ***\n", msg.c_str()); });
  212. }
  213. // syslog example (linux/osx/freebsd)
  214. #ifndef _WIN32
  215. #include "spdlog/sinks/syslog_sink.h"
  216. void syslog_example()
  217. {
  218. std::string ident = "spdlog-example";
  219. auto syslog_logger = spdlog::syslog_logger_mt("syslog", ident, LOG_PID);
  220. syslog_logger->warn("This is warning that will end up in syslog.");
  221. }
  222. #endif
  223. // Android example.
  224. #if defined(__ANDROID__)
  225. #include "spdlog/sinks/android_sink.h"
  226. void android_example()
  227. {
  228. std::string tag = "spdlog-android";
  229. auto android_logger = spdlog::android_logger_mt("android", tag);
  230. android_logger->critical("Use \"adb shell logcat\" to view this message.");
  231. }
  232. #endif
  233. // Log patterns can contain custom flags.
  234. // this will add custom flag '%*' which will be bound to a <my_formatter_flag> instance
  235. #include "spdlog/pattern_formatter.h"
  236. class my_formatter_flag : public spdlog::custom_flag_formatter
  237. {
  238. public:
  239. void format(const spdlog::details::log_msg &, const std::tm &, spdlog::memory_buf_t &dest) override
  240. {
  241. std::string some_txt = "custom-flag";
  242. dest.append(some_txt.data(), some_txt.data() + some_txt.size());
  243. }
  244. std::unique_ptr<custom_flag_formatter> clone() const override
  245. {
  246. return spdlog::details::make_unique<my_formatter_flag>();
  247. }
  248. };
  249. void custom_flags_example()
  250. {
  251. using spdlog::details::make_unique; // for pre c++14
  252. auto formatter = make_unique<spdlog::pattern_formatter>();
  253. formatter->add_flag<my_formatter_flag>('*').set_pattern("[%n] [%*] [%^%l%$] %v");
  254. spdlog::set_formatter(std::move(formatter));
  255. }