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