【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 ", 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 *** ", 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.
顺序 选择 循环 总结