C++ spdlog日志管理


【1】spdlog簡介

spdlog是一個開源的、快速的、僅有頭文件的基於C++11實現的一款C++專用日志管理庫。

【2】源碼下載

下載地址:https://github.com/gabime/spdlog

【3】工程配置

(1)解壓縮源碼包

解壓后,找到include文件夾。類比本地:

注意:include文件夾里是所需的頭文件及源碼。

(2)工程配置

2.1 新建一個C++控制台應用程序空項目spdlog

2.2 在項目屬性頁:VC++目錄->包含目錄 中添加上述include路徑,如下圖:

2.3 在項目中添加頭文件即可,如下:

1 #include "spdlog/spdlog.h"
2 using namespace spdlog;

OK 請盡情享用。是的,沒錯,就是這么簡單,你不用懷疑你自己。。。。

【4】應用示例

為了更權威、更有說服力,遂決定把源碼包中的example示例貼出來(加了若干自己理解的信息)

應用示例如下:

  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 
  9 // 標准輸出類型
 10 void stdout_logger_example();
 11 // 基本類型:日志文件會一直被寫入,不斷變大。
 12 void basic_example();
 13 // 滾動類型:日志文件會先寫入一個文件,當超出規定大小時,會備份(或刪除)當前日志內容,重建文件開始寫入。
 14 /* 說明:從函數聲明可以看出,參數max_file_size規定了文件數量的最大值,當文件數量超過此值就會把最早的先清空。
 15 參數max_file_size規定了滾動文件的個數。當logger_name存滿時,將其名稱更改為logger_name.1,再新建一個logger_name文件來存儲新的日志。
 16 再次存滿時,把logger_name.1改名為logger_name.2,logger_name改名為logger_name.1,再新建一個logger_name來存放新的日志。
 17 以此類推,max_files 數量為幾,就可以有幾個logger_name文件用來滾動。
 18 */
 19 void rotating_example();
 20 // 每日類型:每天新建一個日志,新建日志文件時間可以自定義。
 21 void daily_example();
 22 // 異步模式類型
 23 void async_example();
 24 // 二進制類型
 25 void binary_example();
 26 // 追蹤類型
 27 void trace_example();
 28 // 多匯入類型
 29 /* 帶多接收器的記錄器 - 每個接收器都有不同的格式和日志級別
 30 譬如,創建具有 2 個不同日志級別和格式的目標的記錄器。
 31 控制台將僅顯示警告或錯誤,而文件將記錄所有。
 32 */
 33 void multi_sink_example();
 34 // 自定義類型
 35 void user_defined_example();
 36 // 錯誤處理類型
 37 /*
 38 自定義錯誤處理程序。將在日志失敗時觸發。
 39 可以全局設置或針對性設置
 40 */
 41 void err_handler_example();
 42 // 系統類型 (linux/osx/freebsd)
 43 void syslog_example();
 44 
 45 // 重點備注:
 46 // 日志實時寫入接口:logger->flush();
 47 /*
 48 上述各種日志文件,僅在程序退出時才保存日志。
 49 如果要想在程序運行時也能夠實時保存日志,可以在程序中添加如上語句。
 50 具體參見譬如166行的應用示例
 51 */
 52 
 53 #include "spdlog/spdlog.h"
 54 
 55 int main(int, char* [])
 56 {
 57     spdlog::info("Welcome to spdlog version {}.{}.{}  !", SPDLOG_VER_MAJOR, SPDLOG_VER_MINOR, SPDLOG_VER_PATCH);
 58     spdlog::warn("Easy padding in numbers like {:08d}", 12);
 59     spdlog::critical("Support for int: {0:d};  hex: {0:x};  oct: {0:o}; bin: {0:b}", 42);
 60     spdlog::info("Support for floats {:03.2f}", 1.23456);
 61     spdlog::info("Positional args are {1} {0}..", "too", "supported");
 62     spdlog::info("{:>8} aligned, {:<8} aligned", "right", "left");
 63 
 64     // Runtime log levels
 65     // 支持設置日志級別:低於設置級別的日志將不會被輸出。各level排序詳見源碼,數值越大級別越高:
 66     /*
 67     enum level_enum
 68     {
 69         trace = SPDLOG_LEVEL_TRACE,
 70         debug = SPDLOG_LEVEL_DEBUG,
 71         info = SPDLOG_LEVEL_INFO,
 72         warn = SPDLOG_LEVEL_WARN,
 73         err = SPDLOG_LEVEL_ERROR,
 74         critical = SPDLOG_LEVEL_CRITICAL,
 75         off = SPDLOG_LEVEL_OFF,
 76     };
 77     */
 78     spdlog::set_level(spdlog::level::info); // Set global log level to info
 79     spdlog::debug("This message should not be displayed!");
 80     spdlog::set_level(spdlog::level::trace); // Set specific logger's log level
 81     spdlog::debug("This message should be displayed..");
 82 
 83     // Customize msg format for all loggers
 84     // 支持自定義日志格式
 85     spdlog::set_pattern("[%H:%M:%S %z] [%^%L%$] [thread %t] %v");
 86     spdlog::info("This an info message with custom format");
 87     spdlog::set_pattern("%+"); // back to default format
 88     spdlog::set_level(spdlog::level::info);
 89 
 90     // 支持回溯分析
 91     // Backtrace support
 92     // Loggers can store in a ring buffer all messages (including debug/trace) for later inspection.
 93     // When needed, call dump_backtrace() to see what happened:
 94     spdlog::enable_backtrace(10); // create ring buffer with capacity of 10  messages
 95     for (int i = 0; i < 100; i++)
 96     {
 97         spdlog::debug("Backtrace message {}", i); // not logged.
 98     }
 99     // e.g. if some error happened:
100     spdlog::dump_backtrace(); // log them now!
101 
102     try
103     {
104         stdout_logger_example();
105         basic_example();
106         rotating_example();
107         daily_example();
108         async_example();
109         binary_example();
110         multi_sink_example();
111         user_defined_example();
112         err_handler_example();
113         trace_example();
114 
115         // Flush all *registered* loggers using a worker thread every 3 seconds.
116         // note: registered loggers *must* be thread safe for this to work correctly!
117         spdlog::flush_every(std::chrono::seconds(3));
118 
119         // Apply some function on all registered loggers
120         spdlog::apply_all([&](std::shared_ptr<spdlog::logger> l) { l->info("End of example."); });
121 
122         // Release all spdlog resources, and drop all loggers in the registry.
123         // This is optional (only mandatory if using windows + async log).
124         spdlog::shutdown();
125     }
126 
127     // Exceptions will only be thrown upon failed logger or sink construction (not during logging).
128     catch (const spdlog::spdlog_ex & ex)
129     {
130         std::printf("Log initialization failed: %s\n", ex.what());
131         return 1;
132     }
133 }
134 
135 #include "spdlog/sinks/stdout_color_sinks.h"
136 // or #include "spdlog/sinks/stdout_sinks.h" if no colors needed.
137 void stdout_logger_example()
138 {
139     // Create color multi threaded logger.
140     auto console = spdlog::stdout_color_mt("console");
141     // or for stderr:
142     // auto console = spdlog::stderr_color_mt("error-logger");
143 }
144 
145 #include "spdlog/sinks/basic_file_sink.h"
146 void basic_example()
147 {
148     // Create basic file logger (not rotated).
149     auto my_logger = spdlog::basic_logger_mt("file_logger", "logs/basic-log.txt");
150 }
151 
152 #include "spdlog/sinks/rotating_file_sink.h"
153 void rotating_example()
154 {
155     // Create a file rotating logger with 5mb size max and 3 rotated files.
156     auto rotating_logger = spdlog::rotating_logger_mt("some_logger_name", "logs/rotating.txt", 1048576 * 5, 3);
157     int a = 100, b = 200;
158     rotating_logger->error("error!");
159     rotating_logger->info("a = {}, b = {}, a/b = {}, a%b = {}", a, b, a / b, a % b);
160     rotating_logger->flush();
161 }
162 
163 #include "spdlog/sinks/daily_file_sink.h"
164 void daily_example()
165 {
166     // Create a daily logger - a new file is created every day on 2:30am.
167     auto daily_logger = spdlog::daily_logger_mt("daily_logger", "logs/daily.txt", 2, 30);
168 }
169 
170 #include "spdlog/async.h"
171 void async_example()
172 {
173     // Default thread pool settings can be modified *before* creating the async logger:
174     // spdlog::init_thread_pool(32768, 1); // queue with max 32k items 1 backing thread.
175     auto async_file = spdlog::basic_logger_mt<spdlog::async_factory>("async_file_logger", "logs/async_log.txt");
176     // alternatively:
177     // auto async_file = spdlog::create_async<spdlog::sinks::basic_file_sink_mt>("async_file_logger", "logs/async_log.txt");
178 
179     for (int i = 1; i < 101; ++i)
180     {
181         async_file->info("Async message #{}", i);
182     }
183 }
184 
185 // Log binary data as hex.
186 // Many types of std::container<char> types can be used.
187 // Iterator ranges are supported too.
188 // Format flags:
189 // {:X} - print in uppercase.
190 // {:s} - don't separate each byte with space.
191 // {:p} - don't print the position on each line start.
192 // {:n} - don't split the output to lines.
193 
194 #include "spdlog/fmt/bin_to_hex.h"
195 void binary_example()
196 {
197     std::vector<char> buf;
198     for (int i = 0; i < 80; i++)
199     {
200         buf.push_back(static_cast<char>(i & 0xff));
201     }
202     spdlog::info("Binary example: {}", spdlog::to_hex(buf));
203     spdlog::info("Another binary example:{:n}", spdlog::to_hex(std::begin(buf), std::begin(buf) + 10));
204     // more examples:
205     // logger->info("uppercase: {:X}", spdlog::to_hex(buf));
206     // logger->info("uppercase, no delimiters: {:Xs}", spdlog::to_hex(buf));
207     // logger->info("uppercase, no delimiters, no position info: {:Xsp}", spdlog::to_hex(buf));
208 }
209 
210 // Compile time log levels.
211 // define SPDLOG_ACTIVE_LEVEL to required level (e.g. SPDLOG_LEVEL_TRACE)
212 void trace_example()
213 {
214     // trace from default logger
215     SPDLOG_TRACE("Some trace message.. {} ,{}", 1, 3.23);
216     // debug from default logger
217     SPDLOG_DEBUG("Some debug message.. {} ,{}", 1, 3.23);
218 
219     // trace from logger object
220     auto logger = spdlog::get("file_logger");
221     SPDLOG_LOGGER_TRACE(logger, "another trace message");
222 }
223 
224 // A logger with multiple sinks (stdout and file) - each with a different format and log level.
225 void multi_sink_example()
226 {
227     auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
228     console_sink->set_level(spdlog::level::warn);
229     console_sink->set_pattern("[multi_sink_example] [%^%l%$] %v");
230 
231     auto file_sink = std::make_shared<spdlog::sinks::basic_file_sink_mt>("logs/multisink.txt", true);
232     file_sink->set_level(spdlog::level::trace);
233 
234     spdlog::logger logger("multi_sink", { console_sink, file_sink });
235     logger.set_level(spdlog::level::debug);
236     logger.warn("this should appear in both console and file");
237     logger.info("this message should not appear in the console, only in the file");
238 }
239 
240 // User defined types logging by implementing operator<<
241 #include "spdlog/fmt/ostr.h" // must be included
242 struct my_type
243 {
244     int i;
245     template<typename OStream>
246     friend OStream& operator<<(OStream& os, const my_type& c)
247     {
248         return os << "[my_type i=" << c.i << "]";
249     }
250 };
251 
252 void user_defined_example()
253 {
254     spdlog::info("user defined type: {}", my_type{ 14 });
255 }
256 
257 // Custom error handler. Will be triggered on log failure.
258 void err_handler_example()
259 {
260     // can be set globally or per logger(logger->set_error_handler(..))
261     spdlog::set_error_handler([](const std::string& msg) { printf("*** Custom log error handler: %s ***\n", msg.c_str()); });
262 }
263 
264 // syslog example (linux/osx/freebsd)
265 #ifndef _WIN32
266 #include "spdlog/sinks/syslog_sink.h"
267 void syslog_example()
268 {
269     std::string ident = "spdlog-example";
270     auto syslog_logger = spdlog::syslog_logger_mt("syslog", ident, LOG_PID);
271     syslog_logger->warn("This is warning that will end up in syslog.");
272 }
273 #endif
274 
275 // Android example.
276 #if defined(__ANDROID__)
277 #include "spdlog/sinks/android_sink.h"
278 void android_example()
279 {
280     std::string tag = "spdlog-android";
281     auto android_logger = spdlog::android_logger_mt("android", tag);
282     android_logger->critical("Use \"adb shell logcat\" to view this message.");
283 }
284 
285 #endif

 

good good study, day day up.

順序 選擇 循環 總結


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM