You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

464 lines
16 KiB

4 months ago
  1. # spdlog
  2. Very fast, header-only/compiled, C++ logging library. [![ci](https://github.com/gabime/spdlog/actions/workflows/ci.yml/badge.svg)](https://github.com/gabime/spdlog/actions/workflows/ci.yml)  [![Build status](https://ci.appveyor.com/api/projects/status/d2jnxclg20vd0o50?svg=true&branch=v1.x)](https://ci.appveyor.com/project/gabime/spdlog) [![Release](https://img.shields.io/github/release/gabime/spdlog.svg)](https://github.com/gabime/spdlog/releases/latest)
  3. ## Install
  4. #### Header only version
  5. Copy the include [folder](https://github.com/gabime/spdlog/tree/v1.x/include/spdlog) to your build tree and use a C++11 compiler.
  6. #### Compiled version (recommended - much faster compile times)
  7. ```console
  8. $ git clone https://github.com/gabime/spdlog.git
  9. $ cd spdlog && mkdir build && cd build
  10. $ cmake .. && make -j
  11. ```
  12. see example [CMakeLists.txt](https://github.com/gabime/spdlog/blob/v1.x/example/CMakeLists.txt) on how to use.
  13. ## Platforms
  14. * Linux, FreeBSD, OpenBSD, Solaris, AIX
  15. * Windows (msvc 2013+, cygwin)
  16. * macOS (clang 3.5+)
  17. * Android
  18. ## Package managers:
  19. * Debian: `sudo apt install libspdlog-dev`
  20. * Homebrew: `brew install spdlog`
  21. * MacPorts: `sudo port install spdlog`
  22. * FreeBSD: `pkg install spdlog`
  23. * Fedora: `dnf install spdlog`
  24. * Gentoo: `emerge dev-libs/spdlog`
  25. * Arch Linux: `pacman -S spdlog`
  26. * openSUSE: `sudo zypper in spdlog-devel`
  27. * vcpkg: `vcpkg install spdlog`
  28. * conan: `spdlog/[>=1.4.1]`
  29. * conda: `conda install -c conda-forge spdlog`
  30. * build2: ```depends: spdlog ^1.8.2```
  31. ## Features
  32. * Very fast (see [benchmarks](#benchmarks) below).
  33. * Headers only or compiled
  34. * Feature rich formatting, using the excellent [fmt](https://github.com/fmtlib/fmt) library.
  35. * Asynchronous mode (optional)
  36. * [Custom](https://github.com/gabime/spdlog/wiki/3.-Custom-formatting) formatting.
  37. * Multi/Single threaded loggers.
  38. * Various log targets:
  39. * Rotating log files.
  40. * Daily log files.
  41. * Console logging (colors supported).
  42. * syslog.
  43. * Windows event log.
  44. * Windows debugger (```OutputDebugString(..)```).
  45. * Easily [extendable](https://github.com/gabime/spdlog/wiki/4.-Sinks#implementing-your-own-sink) with custom log targets.
  46. * Log filtering - log levels can be modified in runtime as well as in compile time.
  47. * Support for loading log levels from argv or from environment var.
  48. * [Backtrace](#backtrace-support) support - store debug messages in a ring buffer and display later on demand.
  49. ## Usage samples
  50. #### Basic usage
  51. ```c++
  52. #include "spdlog/spdlog.h"
  53. int main()
  54. {
  55. spdlog::info("Welcome to spdlog!");
  56. spdlog::error("Some error message with arg: {}", 1);
  57. spdlog::warn("Easy padding in numbers like {:08d}", 12);
  58. spdlog::critical("Support for int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42);
  59. spdlog::info("Support for floats {:03.2f}", 1.23456);
  60. spdlog::info("Positional args are {1} {0}..", "too", "supported");
  61. spdlog::info("{:<30}", "left aligned");
  62. spdlog::set_level(spdlog::level::debug); // Set global log level to debug
  63. spdlog::debug("This message should be displayed..");
  64. // change log pattern
  65. spdlog::set_pattern("[%H:%M:%S %z] [%n] [%^---%L---%$] [thread %t] %v");
  66. // Compile time log levels
  67. // define SPDLOG_ACTIVE_LEVEL to desired level
  68. SPDLOG_TRACE("Some trace message with param {}", 42);
  69. SPDLOG_DEBUG("Some debug message");
  70. }
  71. ```
  72. ---
  73. #### Create stdout/stderr logger object
  74. ```c++
  75. #include "spdlog/spdlog.h"
  76. #include "spdlog/sinks/stdout_color_sinks.h"
  77. void stdout_example()
  78. {
  79. // create color multi threaded logger
  80. auto console = spdlog::stdout_color_mt("console");
  81. auto err_logger = spdlog::stderr_color_mt("stderr");
  82. spdlog::get("console")->info("loggers can be retrieved from a global registry using the spdlog::get(logger_name)");
  83. }
  84. ```
  85. ---
  86. #### Basic file logger
  87. ```c++
  88. #include "spdlog/sinks/basic_file_sink.h"
  89. void basic_logfile_example()
  90. {
  91. try
  92. {
  93. auto logger = spdlog::basic_logger_mt("basic_logger", "logs/basic-log.txt");
  94. }
  95. catch (const spdlog::spdlog_ex &ex)
  96. {
  97. std::cout << "Log init failed: " << ex.what() << std::endl;
  98. }
  99. }
  100. ```
  101. ---
  102. #### Rotating files
  103. ```c++
  104. #include "spdlog/sinks/rotating_file_sink.h"
  105. void rotating_example()
  106. {
  107. // Create a file rotating logger with 5mb size max and 3 rotated files
  108. auto max_size = 1048576 * 5;
  109. auto max_files = 3;
  110. auto logger = spdlog::rotating_logger_mt("some_logger_name", "logs/rotating.txt", max_size, max_files);
  111. }
  112. ```
  113. ---
  114. #### Daily files
  115. ```c++
  116. #include "spdlog/sinks/daily_file_sink.h"
  117. void daily_example()
  118. {
  119. // Create a daily logger - a new file is created every day on 2:30am
  120. auto logger = spdlog::daily_logger_mt("daily_logger", "logs/daily.txt", 2, 30);
  121. }
  122. ```
  123. ---
  124. #### Backtrace support
  125. ```c++
  126. // Debug messages can be stored in a ring buffer instead of being logged immediately.
  127. // This is useful in order to display debug logs only when really needed (e.g. when error happens).
  128. // When needed, call dump_backtrace() to see them.
  129. spdlog::enable_backtrace(32); // Store the latest 32 messages in a buffer. Older messages will be dropped.
  130. // or my_logger->enable_backtrace(32)..
  131. for(int i = 0; i < 100; i++)
  132. {
  133. spdlog::debug("Backtrace message {}", i); // not logged yet..
  134. }
  135. // e.g. if some error happened:
  136. spdlog::dump_backtrace(); // log them now! show the last 32 messages
  137. // or my_logger->dump_backtrace(32)..
  138. ```
  139. ---
  140. #### Periodic flush
  141. ```c++
  142. // periodically flush all *registered* loggers every 3 seconds:
  143. // warning: only use if all your loggers are thread safe ("_mt" loggers)
  144. spdlog::flush_every(std::chrono::seconds(3));
  145. ```
  146. ---
  147. #### Stopwatch
  148. ```c++
  149. // Stopwatch support for spdlog
  150. #include "spdlog/stopwatch.h"
  151. void stopwatch_example()
  152. {
  153. spdlog::stopwatch sw;
  154. spdlog::debug("Elapsed {}", sw);
  155. spdlog::debug("Elapsed {:.3}", sw);
  156. }
  157. ```
  158. ---
  159. #### Log binary data in hex
  160. ```c++
  161. // many types of std::container<char> types can be used.
  162. // ranges are supported too.
  163. // format flags:
  164. // {:X} - print in uppercase.
  165. // {:s} - don't separate each byte with space.
  166. // {:p} - don't print the position on each line start.
  167. // {:n} - don't split the output to lines.
  168. // {:a} - show ASCII if :n is not set.
  169. #include "spdlog/fmt/bin_to_hex.h"
  170. void binary_example()
  171. {
  172. auto console = spdlog::get("console");
  173. std::array<char, 80> buf;
  174. console->info("Binary example: {}", spdlog::to_hex(buf));
  175. console->info("Another binary example:{:n}", spdlog::to_hex(std::begin(buf), std::begin(buf) + 10));
  176. // more examples:
  177. // logger->info("uppercase: {:X}", spdlog::to_hex(buf));
  178. // logger->info("uppercase, no delimiters: {:Xs}", spdlog::to_hex(buf));
  179. // logger->info("uppercase, no delimiters, no position info: {:Xsp}", spdlog::to_hex(buf));
  180. }
  181. ```
  182. ---
  183. #### Logger with multi sinks - each with different format and log level
  184. ```c++
  185. // create logger with 2 targets with different log levels and formats.
  186. // the console will show only warnings or errors, while the file will log all.
  187. void multi_sink_example()
  188. {
  189. auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
  190. console_sink->set_level(spdlog::level::warn);
  191. console_sink->set_pattern("[multi_sink_example] [%^%l%$] %v");
  192. auto file_sink = std::make_shared<spdlog::sinks::basic_file_sink_mt>("logs/multisink.txt", true);
  193. file_sink->set_level(spdlog::level::trace);
  194. spdlog::logger logger("multi_sink", {console_sink, file_sink});
  195. logger.set_level(spdlog::level::debug);
  196. logger.warn("this should appear in both console and file");
  197. logger.info("this message should not appear in the console, only in the file");
  198. }
  199. ```
  200. ---
  201. #### Asynchronous logging
  202. ```c++
  203. #include "spdlog/async.h"
  204. #include "spdlog/sinks/basic_file_sink.h"
  205. void async_example()
  206. {
  207. // default thread pool settings can be modified *before* creating the async logger:
  208. // spdlog::init_thread_pool(8192, 1); // queue with 8k items and 1 backing thread.
  209. auto async_file = spdlog::basic_logger_mt<spdlog::async_factory>("async_file_logger", "logs/async_log.txt");
  210. // alternatively:
  211. // auto async_file = spdlog::create_async<spdlog::sinks::basic_file_sink_mt>("async_file_logger", "logs/async_log.txt");
  212. }
  213. ```
  214. ---
  215. #### Asynchronous logger with multi sinks
  216. ```c++
  217. #include "spdlog/sinks/stdout_color_sinks.h"
  218. #include "spdlog/sinks/rotating_file_sink.h"
  219. void multi_sink_example2()
  220. {
  221. spdlog::init_thread_pool(8192, 1);
  222. auto stdout_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt >();
  223. auto rotating_sink = std::make_shared<spdlog::sinks::rotating_file_sink_mt>("mylog.txt", 1024*1024*10, 3);
  224. std::vector<spdlog::sink_ptr> sinks {stdout_sink, rotating_sink};
  225. auto logger = std::make_shared<spdlog::async_logger>("loggername", sinks.begin(), sinks.end(), spdlog::thread_pool(), spdlog::async_overflow_policy::block);
  226. spdlog::register_logger(logger);
  227. }
  228. ```
  229. ---
  230. #### User defined types
  231. ```c++
  232. template<>
  233. struct fmt::formatter<my_type> : fmt::formatter<std::string>
  234. {
  235. auto format(my_type my, format_context &ctx) -> decltype(ctx.out())
  236. {
  237. return format_to(ctx.out(), "[my_type i={}]", my.i);
  238. }
  239. };
  240. void user_defined_example()
  241. {
  242. spdlog::info("user defined type: {}", my_type(14));
  243. }
  244. ```
  245. ---
  246. #### User defined flags in the log pattern
  247. ```c++
  248. // Log patterns can contain custom flags.
  249. // the following example will add new flag '%*' - which will be bound to a <my_formatter_flag> instance.
  250. #include "spdlog/pattern_formatter.h"
  251. class my_formatter_flag : public spdlog::custom_flag_formatter
  252. {
  253. public:
  254. void format(const spdlog::details::log_msg &, const std::tm &, spdlog::memory_buf_t &dest) override
  255. {
  256. std::string some_txt = "custom-flag";
  257. dest.append(some_txt.data(), some_txt.data() + some_txt.size());
  258. }
  259. std::unique_ptr<custom_flag_formatter> clone() const override
  260. {
  261. return spdlog::details::make_unique<my_formatter_flag>();
  262. }
  263. };
  264. void custom_flags_example()
  265. {
  266. auto formatter = std::make_unique<spdlog::pattern_formatter>();
  267. formatter->add_flag<my_formatter_flag>('*').set_pattern("[%n] [%*] [%^%l%$] %v");
  268. spdlog::set_formatter(std::move(formatter));
  269. }
  270. ```
  271. ---
  272. #### Custom error handler
  273. ```c++
  274. void err_handler_example()
  275. {
  276. // can be set globally or per logger(logger->set_error_handler(..))
  277. spdlog::set_error_handler([](const std::string &msg) { spdlog::get("console")->error("*** LOGGER ERROR ***: {}", msg); });
  278. spdlog::get("console")->info("some invalid message to trigger an error {}{}{}{}", 3);
  279. }
  280. ```
  281. ---
  282. #### syslog
  283. ```c++
  284. #include "spdlog/sinks/syslog_sink.h"
  285. void syslog_example()
  286. {
  287. std::string ident = "spdlog-example";
  288. auto syslog_logger = spdlog::syslog_logger_mt("syslog", ident, LOG_PID);
  289. syslog_logger->warn("This is warning that will end up in syslog.");
  290. }
  291. ```
  292. ---
  293. #### Android example
  294. ```c++
  295. #include "spdlog/sinks/android_sink.h"
  296. void android_example()
  297. {
  298. std::string tag = "spdlog-android";
  299. auto android_logger = spdlog::android_logger_mt("android", tag);
  300. android_logger->critical("Use \"adb shell logcat\" to view this message.");
  301. }
  302. ```
  303. ---
  304. #### Load log levels from env variable or from argv
  305. ```c++
  306. #include "spdlog/cfg/env.h"
  307. int main (int argc, char *argv[])
  308. {
  309. spdlog::cfg::load_env_levels();
  310. // or from command line:
  311. // ./example SPDLOG_LEVEL=info,mylogger=trace
  312. // #include "spdlog/cfg/argv.h" // for loading levels from argv
  313. // spdlog::cfg::load_argv_levels(argc, argv);
  314. }
  315. ```
  316. So then you can:
  317. ```console
  318. $ export SPDLOG_LEVEL=info,mylogger=trace
  319. $ ./example
  320. ```
  321. ---
  322. #### Log file open/close event handlers
  323. ```c++
  324. // You can get callbacks from spdlog before/after log file has been opened or closed.
  325. // This is useful for cleanup procedures or for adding someting the start/end of the log files.
  326. void file_events_example()
  327. {
  328. // pass the spdlog::file_event_handlers to file sinks for open/close log file notifications
  329. spdlog::file_event_handlers handlers;
  330. handlers.before_open = [](spdlog::filename_t filename) { spdlog::info("Before opening {}", filename); };
  331. handlers.after_open = [](spdlog::filename_t filename, std::FILE *fstream) { fputs("After opening\n", fstream); };
  332. handlers.before_close = [](spdlog::filename_t filename, std::FILE *fstream) { fputs("Before closing\n", fstream); };
  333. handlers.after_close = [](spdlog::filename_t filename) { spdlog::info("After closing {}", filename); };
  334. auto my_logger = spdlog::basic_logger_st("some_logger", "logs/events-sample.txt", true, handlers);
  335. }
  336. ```
  337. ---
  338. #### Replace the Default Logger
  339. ```c++
  340. void replace_default_logger_example()
  341. {
  342. auto new_logger = spdlog::basic_logger_mt("new_default_logger", "logs/new-default-log.txt", true);
  343. spdlog::set_default_logger(new_logger);
  344. spdlog::info("new logger log message");
  345. }
  346. ```
  347. ---
  348. ## Benchmarks
  349. Below are some [benchmarks](https://github.com/gabime/spdlog/blob/v1.x/bench/bench.cpp) done in Ubuntu 64 bit, Intel i7-4770 CPU @ 3.40GHz
  350. #### Synchronous mode
  351. ```
  352. [info] **************************************************************
  353. [info] Single thread, 1,000,000 iterations
  354. [info] **************************************************************
  355. [info] basic_st Elapsed: 0.17 secs 5,777,626/sec
  356. [info] rotating_st Elapsed: 0.18 secs 5,475,894/sec
  357. [info] daily_st Elapsed: 0.20 secs 5,062,659/sec
  358. [info] empty_logger Elapsed: 0.07 secs 14,127,300/sec
  359. [info] **************************************************************
  360. [info] C-string (400 bytes). Single thread, 1,000,000 iterations
  361. [info] **************************************************************
  362. [info] basic_st Elapsed: 0.41 secs 2,412,483/sec
  363. [info] rotating_st Elapsed: 0.72 secs 1,389,196/sec
  364. [info] daily_st Elapsed: 0.42 secs 2,393,298/sec
  365. [info] null_st Elapsed: 0.04 secs 27,446,957/sec
  366. [info] **************************************************************
  367. [info] 10 threads, competing over the same logger object, 1,000,000 iterations
  368. [info] **************************************************************
  369. [info] basic_mt Elapsed: 0.60 secs 1,659,613/sec
  370. [info] rotating_mt Elapsed: 0.62 secs 1,612,493/sec
  371. [info] daily_mt Elapsed: 0.61 secs 1,638,305/sec
  372. [info] null_mt Elapsed: 0.16 secs 6,272,758/sec
  373. ```
  374. #### Asynchronous mode
  375. ```
  376. [info] -------------------------------------------------
  377. [info] Messages : 1,000,000
  378. [info] Threads : 10
  379. [info] Queue : 8,192 slots
  380. [info] Queue memory : 8,192 x 272 = 2,176 KB
  381. [info] -------------------------------------------------
  382. [info]
  383. [info] *********************************
  384. [info] Queue Overflow Policy: block
  385. [info] *********************************
  386. [info] Elapsed: 1.70784 secs 585,535/sec
  387. [info] Elapsed: 1.69805 secs 588,910/sec
  388. [info] Elapsed: 1.7026 secs 587,337/sec
  389. [info]
  390. [info] *********************************
  391. [info] Queue Overflow Policy: overrun
  392. [info] *********************************
  393. [info] Elapsed: 0.372816 secs 2,682,285/sec
  394. [info] Elapsed: 0.379758 secs 2,633,255/sec
  395. [info] Elapsed: 0.373532 secs 2,677,147/sec
  396. ```
  397. ## Documentation
  398. Documentation can be found in the [wiki](https://github.com/gabime/spdlog/wiki/1.-QuickStart) pages.
  399. ---
  400. Thanks to [JetBrains](https://www.jetbrains.com/?from=spdlog) for donating product licenses to help develop **spdlog** <a href="https://www.jetbrains.com/?from=spdlog"><img src="logos/jetbrains-variant-4.svg" width="94" align="center" /></a>