12.16 log庫spdlog簡介及使用

spdlog是一個開源的、快速的、僅有頭文件的C++11 日誌庫,code地址在 https://github.com/gabime/spdlog ,目前最新的發佈版本為0.14.0。它提供了向流、標準輸出、文件、系統日誌、調試器等目標輸出日誌的能力。它支持的平臺包括Windows、Linux、Mac、Android。

spdlog特性:

(1)、非常快,性能是它的主要目標;

(2)、僅包括頭文件;

(3)、日誌的格式化處理使用開源的fmt庫( https://github.com/fmtlib/fmt );

(4)、可選的printf語法支持;

(5)、非常快的異步模式(可選),支持異步寫日誌;

(6)、自定義格式;

(7)、條件日誌;

(8)、多線程/單線程日誌;

(9)、各種日誌目標:可對日誌文件進行循環輸出;可每日生成日誌文件;支持控制檯日誌輸出(支持顏色);系統日誌;Windows debugger;較容易擴展自定義日誌目標;

(10)、支持日誌輸出級別:閾值級別既可以在運行時也可以在編譯時修改。

以下是測試代碼,主要來自spdlog/example/example.cpp:

#include "funset.hpp"
#include <iostream>
#include "spdlog/spdlog.h"
#include "spdlog/fmt/ostr.h"

namespace spd = spdlog;

int test_spdlog_console()
{
\ttry {
\t\t// Console logger with color
\t\tauto console = spd::stdout_color_mt("console");
\t\tconsole->info("Welcome to spdlog!");
\t\tconsole->error("Some error message with arg{}..", 1);

\t\t// Conditional logging example
\t\tconsole->info_if(true, "Welcome to spdlog conditional logging!");

\t\t// Formatting examples
\t\tconsole->warn("Easy padding in numbers like {:08d}", 12);
\t\tconsole->critical("Support for int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42);
\t\tconsole->info("Support for floats {:03.2f}", 1.23456);
\t\tconsole->info("Positional args are {1} {0}..", "too", "supported");
\t\tconsole->info("{:<30}", "left aligned");

\t\tSPDLOG_DEBUG_IF(console, true, "This is a debug log");

\t\tspd::get("console")->info("loggers can be retrieved from a global registry using the spdlog::get(logger_name) function");

\t\t// Create basic file logger (not rotated)
\t\tauto my_logger = spd::basic_logger_mt("basic_logger", "E:/GitCode/Messy_Test/testdata/basic_log");
\t\tmy_logger->info("Some log message");

\t\t// Create a file rotating logger with 5mb size max and 3 rotated files
\t\tauto rotating_logger = spd::rotating_logger_mt("some_logger_name", "E:/GitCode/Messy_Test/testdata/mylogfile_log", 1048576 * 5, 3);
\t\tfor (int i = 0; i < 10; ++i)
\t\t\trotating_logger->info("{} * {} equals {:>10}", i, i, i*i);

\t\t// Create a daily logger - a new file is created every day on 2:30am
\t\tauto daily_logger = spd::daily_logger_mt("daily_logger", "E:/GitCode/Messy_Test/testdata/daily_log", 2, 30);
\t\t// trigger flush if the log severity is error or higher
\t\tdaily_logger->flush_on(spd::level::err);
\t\tdaily_logger->info(123.44);

\t\t// Customize msg format for all messages
\t\tspd::set_pattern("*** [%H:%M:%S %z] [thread %t] %v ***");
\t\trotating_logger->info("This is another message with custom format");

\t\t// Runtime log levels
\t\tspd::set_level(spd::level::info); //Set global log level to info
\t\tconsole->debug("This message shold not be displayed!");
\t\tconsole->set_level(spd::level::debug); // Set specific logger's log level
\t\tconsole->debug("This message shold be displayed..");

\t\t// Compile time log levels

\t\t// define SPDLOG_DEBUG_ON or SPDLOG_TRACE_ON
\t\tSPDLOG_TRACE(console, "Enabled only #ifdef SPDLOG_TRACE_ON..{} ,{}", 1, 3.23);
\t\tSPDLOG_DEBUG(console, "Enabled only #ifdef SPDLOG_DEBUG_ON.. {} ,{}", 1, 3.23);
\t\tSPDLOG_DEBUG_IF(console, true, "This is a debug log");

\t\t// Apply a function on all registered loggers
\t\tspd::apply_all([&](std::shared_ptr<:logger> l) { l->info("End of example."); });

\t\t// Release and close all loggers
\t\tspdlog::drop_all();
\t}
\t// Exceptions will only be thrown upon failed logger or sink construction (not during logging)
\tcatch (const spd::spdlog_ex& ex) {
\t\tstd::cout << "Log init failed: " << ex.what() << std::endl;
\t\treturn -1;
\t}

\treturn 0;
}

int test_spdlog_async()
{
\t// Asynchronous logging is very fast..
\t// Just call spdlog::set_async_mode(q_size) and all created loggers from now on will be asynchronous..
\tsize_t q_size = 4096; //queue size must be power of 2
\tspdlog::set_async_mode(q_size);
\tauto async_file = spd::daily_logger_st("async_file_logger", "E:/GitCode/Messy_Test/testdata/async_log");

\tfor (int i = 0; i < 100; ++i)
\t\tasync_file->info("Async message #{}", i);

\treturn 0;
}

int test_spdlog_syslog()
{
\t// there is no syslog.h file in windows, so macro SPDLOG_ENABLE_SYSLOG should be disenable
#ifdef SPDLOG_ENABLE_SYSLOG
\tstd::string ident = "spdlog-example";
\tauto syslog_logger = spd::syslog_logger("syslog", ident, LOG_PID);
\tsyslog_logger->warn("This is warning that will end up in syslog.");
#endif

\treturn 0;
}
// user defined types logging by implementing operator<<
struct my_type {
\tint i;
\ttemplate<typename>

\tfriend OStream& operator<\t{
\t\treturn os << "[my_type i=" << c.i << "]";
\t}
};
int test_spdlog_user_defined()
{
\ttry {
\t\t//spd::get("console")->info("user defined type: {}", my_type{ 14 });
\t\tauto console = spd::stdout_color_mt("console");
\t\tconsole->info("user defined type: {}", my_type{ 14 });
\t} catch (const spd::spdlog_ex& ex) {
\t\tstd::cout << "user defined log fail: " << ex.what() << std::endl;
\t\treturn -1;
\t}
\treturn 0;
}
int test_spdlog_err_handler()
{
\t// can be set globaly or per logger(logger->set_error_handler(..))
\tspdlog::set_error_handler([](const std::string& msg)
\t{
\t\tstd::cerr << "my err handler: " << msg << std::endl;
\t});
\t//spd::get("console")->info("some invalid message to trigger an error {}{}{}{}", 3);
\tauto console = spd::stdout_color_mt("console");
\tconsole->info("some invalid message to trigger an error {}{}{}{}", 3);
\treturn 0;
}/<typename>/<iostream>

最後,如果你想學C/C++可以私信小編“01”獲取素材資料以及開發工具和聽課權限哦!


分享到:


相關文章: