• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..13-Nov-2021-

bench/H03-May-2022-726519

cmake/H13-Nov-2021-473402

example/H03-May-2022-295193

include/spdlog/H13-Nov-2021-22,71317,051

logos/H03-May-2022-

scripts/H13-Nov-2021-3523

src/H13-Nov-2021-252182

tests/H03-May-2022-18,09213,910

.gitignoreH A D13-Nov-2021936 8473

INSTALLH A D13-Nov-2021661 2516

LICENSEH A D13-Nov-20211.3 KiB2720

README.mdH A D13-Nov-202114.4 KiB434372

README.md

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