mirror of
https://github.com/gabime/spdlog.git
synced 2025-04-01 02:42:41 +08:00
no exceptions while logging
This commit is contained in:
parent
2fc332abdc
commit
39cdd08a54
137
README.md
137
README.md
@ -10,7 +10,6 @@ Just copy the source [folder](https://github.com/gabime/spdlog/tree/master/inclu
|
|||||||
* Linux (gcc 4.8.1+, clang 3.5+)
|
* Linux (gcc 4.8.1+, clang 3.5+)
|
||||||
* Windows (visual studio 2013+, cygwin/mingw with g++ 4.9.1+)
|
* Windows (visual studio 2013+, cygwin/mingw with g++ 4.9.1+)
|
||||||
* Mac OSX (clang 3.5+)
|
* Mac OSX (clang 3.5+)
|
||||||
* FreeBSD (gcc 4.8.1+)
|
|
||||||
|
|
||||||
##Features
|
##Features
|
||||||
* Very fast - performance is the primary goal (see [benchmarks](#benchmarks) below).
|
* Very fast - performance is the primary goal (see [benchmarks](#benchmarks) below).
|
||||||
@ -58,22 +57,36 @@ Time needed to log 1,000,000 lines in asynchronous mode, i.e. the time it takes
|
|||||||
|
|
||||||
## Usage Example
|
## Usage Example
|
||||||
```c++
|
```c++
|
||||||
#include <iostream>
|
//
|
||||||
|
// Copyright(c) 2015 Gabi Melman.
|
||||||
|
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||||
|
//
|
||||||
|
//
|
||||||
|
// spdlog usage example
|
||||||
|
//
|
||||||
#include "spdlog/spdlog.h"
|
#include "spdlog/spdlog.h"
|
||||||
|
|
||||||
int main(int, char* [])
|
#include <iostream>
|
||||||
|
#include <memory>
|
||||||
|
|
||||||
|
void async_example();
|
||||||
|
void syslog_example();
|
||||||
|
void user_defined_example();
|
||||||
|
void err_handler_example();
|
||||||
|
|
||||||
|
namespace spd = spdlog;
|
||||||
|
int main(int, char*[])
|
||||||
{
|
{
|
||||||
namespace spd = spdlog;
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
// console logger (multithreaded and with color)
|
// Multithreaded color console
|
||||||
auto console = spd::stdout_logger_mt("console", true);
|
auto console = spd::stdout_logger_mt("console", true);
|
||||||
console->info("Welcome to spdlog!") ;
|
console->info("Welcome to spdlog!");
|
||||||
console->info("An info message example {}..", 1);
|
console->error("An info message example {}..", 1);
|
||||||
|
|
||||||
//Formatting examples
|
// Formatting examples
|
||||||
console->info("Easy padding in numbers like {:08d}", 12);
|
console->warn("Easy padding in numbers like {:08d}", 12);
|
||||||
console->info("Support for int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42);
|
console->critical("Support for int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42);
|
||||||
console->info("Support for floats {:03.2f}", 1.23456);
|
console->info("Support for floats {:03.2f}", 1.23456);
|
||||||
console->info("Positional args are {1} {0}..", "too", "supported");
|
console->info("Positional args are {1} {0}..", "too", "supported");
|
||||||
|
|
||||||
@ -81,72 +94,110 @@ int main(int, char* [])
|
|||||||
console->info("{:>30}", "right aligned");
|
console->info("{:>30}", "right aligned");
|
||||||
console->info("{:^30}", "centered");
|
console->info("{:^30}", "centered");
|
||||||
|
|
||||||
//
|
spd::get("console")->info("loggers can be retrieved from a global registry using the spdlog::get(logger_name) function");
|
||||||
|
|
||||||
// Runtime log levels
|
// Runtime log levels
|
||||||
//
|
|
||||||
spd::set_level(spd::level::info); //Set global log level to info
|
spd::set_level(spd::level::info); //Set global log level to info
|
||||||
console->debug("This message shold not be displayed!");
|
console->debug("This message shold not be displayed!");
|
||||||
console->set_level(spd::level::debug); // Set specific logger's log level
|
console->set_level(spd::level::debug); // Set specific logger's log level
|
||||||
console->debug("Now it should..");
|
console->debug("This message shold be displayed..");
|
||||||
|
|
||||||
//
|
// Create basic file logger (not rotated)
|
||||||
// Create a basic multithreaded file logger (or "basic_logger_st" for single threaded logger)
|
|
||||||
//
|
|
||||||
auto my_logger = spd::basic_logger_mt("basic_logger", "logs/basic.txt");
|
auto my_logger = spd::basic_logger_mt("basic_logger", "logs/basic.txt");
|
||||||
my_logger->info("Some log message");
|
my_logger->info("Some log message");
|
||||||
|
|
||||||
//
|
|
||||||
// Create a file rotating logger with 5mb size max and 3 rotated files
|
// Create a file rotating logger with 5mb size max and 3 rotated files
|
||||||
//
|
|
||||||
auto rotating_logger = spd::rotating_logger_mt("some_logger_name", "logs/mylogfile", 1048576 * 5, 3);
|
auto rotating_logger = spd::rotating_logger_mt("some_logger_name", "logs/mylogfile", 1048576 * 5, 3);
|
||||||
for(int i = 0; i < 10; ++i)
|
for (int i = 0; i < 10; ++i)
|
||||||
rotating_logger->info("{} * {} equals {:>10}", i, i, i*i);
|
rotating_logger->info("{} * {} equals {:>10}", i, i, i*i);
|
||||||
|
|
||||||
//
|
// Create a daily logger - a new file is created every day on 2:30am
|
||||||
// Create a daily logger - a new file is created every day at 2:30am
|
|
||||||
//
|
|
||||||
auto daily_logger = spd::daily_logger_mt("daily_logger", "logs/daily", 2, 30);
|
auto daily_logger = spd::daily_logger_mt("daily_logger", "logs/daily", 2, 30);
|
||||||
|
daily_logger->info(123.44);
|
||||||
|
|
||||||
//
|
|
||||||
// Customize msg format for all messages
|
// Customize msg format for all messages
|
||||||
//
|
|
||||||
spd::set_pattern("*** [%H:%M:%S %z] [thread %t] %v ***");
|
spd::set_pattern("*** [%H:%M:%S %z] [thread %t] %v ***");
|
||||||
rotating_logger->info("This is another message with custom format");
|
rotating_logger->info("This is another message with custom format");
|
||||||
|
|
||||||
spd::get("console")->info("loggers can be retrieved from a global registry using the spdlog::get(logger_name) function");
|
|
||||||
|
|
||||||
//
|
|
||||||
// Compile time debug or trace macros.
|
// Compile time debug or trace macros.
|
||||||
// Enabled #ifdef SPDLOG_DEBUG_ON or #ifdef SPDLOG_TRACE_ON
|
// Enabled #ifdef SPDLOG_DEBUG_ON or #ifdef SPDLOG_TRACE_ON
|
||||||
//
|
|
||||||
SPDLOG_TRACE(console, "Enabled only #ifdef SPDLOG_TRACE_ON..{} ,{}", 1, 3.23);
|
SPDLOG_TRACE(console, "Enabled only #ifdef SPDLOG_TRACE_ON..{} ,{}", 1, 3.23);
|
||||||
SPDLOG_DEBUG(console, "Enabled only #ifdef SPDLOG_DEBUG_ON.. {} ,{}", 1, 3.23);
|
SPDLOG_DEBUG(console, "Enabled only #ifdef SPDLOG_DEBUG_ON.. {} ,{}", 1, 3.23);
|
||||||
|
|
||||||
//
|
|
||||||
// Asynchronous logging is very fast..
|
// Asynchronous logging is very fast..
|
||||||
// Just call spdlog::set_async_mode(q_size) and all created loggers from now on will be asynchronous..
|
// Just call spdlog::set_async_mode(q_size) and all created loggers from now on will be asynchronous..
|
||||||
//
|
async_example();
|
||||||
size_t q_size = 8192; //queue size must be power of 2
|
|
||||||
spdlog::set_async_mode(q_size);
|
|
||||||
auto async_file= spd::daily_logger_st("async_file_logger", "logs/async_log.txt");
|
|
||||||
async_file->info("This is async log..Should be very fast!");
|
|
||||||
|
|
||||||
//
|
// syslog example. linux/osx only..
|
||||||
// syslog example. linux only..
|
syslog_example();
|
||||||
//
|
|
||||||
#ifdef __linux__
|
|
||||||
std::string ident = "spdlog-example";
|
|
||||||
auto syslog_logger = spd::syslog_logger("syslog", ident, LOG_PID);
|
|
||||||
syslog_logger->warn("This is warning that will end up in syslog. This is Linux only!");
|
|
||||||
#endif
|
|
||||||
|
|
||||||
|
// log user-defined types example..
|
||||||
|
user_defined_example();
|
||||||
|
|
||||||
|
// Change default log error handler
|
||||||
|
err_handler_example();
|
||||||
|
|
||||||
|
console->info("End of example. bye..");
|
||||||
|
|
||||||
|
// Release and close all loggers
|
||||||
|
spdlog::drop_all();
|
||||||
}
|
}
|
||||||
|
// Exceptions will only be thrown upon failed logger or sink construction (not during logging)
|
||||||
catch (const spd::spdlog_ex& ex)
|
catch (const spd::spdlog_ex& ex)
|
||||||
{
|
{
|
||||||
std::cout << "Log failed: " << ex.what() << std::endl;
|
std::cout << "Log init failed: " << ex.what() << std::endl;
|
||||||
|
return 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void async_example()
|
||||||
|
{
|
||||||
|
size_t q_size = 4096; //queue size must be power of 2
|
||||||
|
spdlog::set_async_mode(q_size);
|
||||||
|
auto async_file = spd::daily_logger_st("async_file_logger", "logs/async_log.txt");
|
||||||
|
for (int i = 0; i < 100; ++i)
|
||||||
|
async_file->info("Async message #{}{}", i);
|
||||||
|
}
|
||||||
|
|
||||||
|
//syslog example (linux/osx only)
|
||||||
|
void syslog_example()
|
||||||
|
{
|
||||||
|
#if defined (__linux__) || defined(__APPLE__)
|
||||||
|
std::string ident = "spdlog-example";
|
||||||
|
auto syslog_logger = spd::syslog_logger("syslog", ident, LOG_PID);
|
||||||
|
syslog_logger->warn("This is warning that will end up in syslog. This is Linux only!");
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
// user defined types logging by implementing operator<<
|
||||||
|
struct my_type
|
||||||
|
{
|
||||||
|
int i;
|
||||||
|
template<typename OStream>
|
||||||
|
friend OStream& operator<<(OStream& os, const my_type &c)
|
||||||
|
{
|
||||||
|
return os << "[my_type i="<<c.i << "]";
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
#include <spdlog/fmt/ostr.h> // must be included
|
||||||
|
void user_defined_example()
|
||||||
|
{
|
||||||
|
spd::get("console")->info("user defined type: {}", my_type { 14 });
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
//custom error handler
|
||||||
|
//
|
||||||
|
void err_handler_example()
|
||||||
|
{
|
||||||
|
//can be set globaly or per logger (logger->set_error_handler(..))
|
||||||
|
spdlog::set_error_handler([](const std::string& msg) {
|
||||||
|
std::cerr << "my err handler: " << msg << std::endl;
|
||||||
|
});
|
||||||
|
spd::get("console")->info("some invalid message to trigger an error {}{}{}{}", 3);
|
||||||
|
}
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -7,13 +7,13 @@
|
|||||||
//
|
//
|
||||||
#include "spdlog/spdlog.h"
|
#include "spdlog/spdlog.h"
|
||||||
|
|
||||||
#include <cstdlib> // EXIT_FAILURE
|
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
#include <memory>
|
#include <memory>
|
||||||
|
|
||||||
void async_example();
|
void async_example();
|
||||||
void syslog_example();
|
void syslog_example();
|
||||||
void user_defined_example();
|
void user_defined_example();
|
||||||
|
void err_handler_example();
|
||||||
|
|
||||||
namespace spd = spdlog;
|
namespace spd = spdlog;
|
||||||
int main(int, char*[])
|
int main(int, char*[])
|
||||||
@ -61,7 +61,6 @@ int main(int, char*[])
|
|||||||
spd::set_pattern("*** [%H:%M:%S %z] [thread %t] %v ***");
|
spd::set_pattern("*** [%H:%M:%S %z] [thread %t] %v ***");
|
||||||
rotating_logger->info("This is another message with custom format");
|
rotating_logger->info("This is another message with custom format");
|
||||||
|
|
||||||
|
|
||||||
// Compile time debug or trace macros.
|
// Compile time debug or trace macros.
|
||||||
// Enabled #ifdef SPDLOG_DEBUG_ON or #ifdef SPDLOG_TRACE_ON
|
// Enabled #ifdef SPDLOG_DEBUG_ON or #ifdef SPDLOG_TRACE_ON
|
||||||
SPDLOG_TRACE(console, "Enabled only #ifdef SPDLOG_TRACE_ON..{} ,{}", 1, 3.23);
|
SPDLOG_TRACE(console, "Enabled only #ifdef SPDLOG_TRACE_ON..{} ,{}", 1, 3.23);
|
||||||
@ -77,27 +76,29 @@ int main(int, char*[])
|
|||||||
// log user-defined types example..
|
// log user-defined types example..
|
||||||
user_defined_example();
|
user_defined_example();
|
||||||
|
|
||||||
|
// Change default log error handler
|
||||||
|
err_handler_example();
|
||||||
|
|
||||||
|
console->info("End of example. bye..");
|
||||||
|
|
||||||
// Release and close all loggers
|
// Release and close all loggers
|
||||||
spdlog::drop_all();
|
spdlog::drop_all();
|
||||||
}
|
}
|
||||||
|
// Exceptions will only be thrown upon failed logger or sink construction (not during logging)
|
||||||
catch (const spd::spdlog_ex& ex)
|
catch (const spd::spdlog_ex& ex)
|
||||||
{
|
{
|
||||||
std::cout << "Log failed: " << ex.what() << std::endl;
|
std::cout << "Log init failed: " << ex.what() << std::endl;
|
||||||
return EXIT_FAILURE;
|
return 1;
|
||||||
}
|
}
|
||||||
return EXIT_SUCCESS;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
void async_example()
|
void async_example()
|
||||||
{
|
{
|
||||||
size_t q_size = 4096; //queue size must be power of 2
|
size_t q_size = 4096; //queue size must be power of 2
|
||||||
spdlog::set_async_mode(q_size);
|
spdlog::set_async_mode(q_size);
|
||||||
auto async_file = spd::daily_logger_st("async_file_logger", "logs/async_log.txt");
|
auto async_file = spd::daily_logger_st("async_file_logger", "logs/async_log.txt");
|
||||||
for (int i = 0; i < 100; ++i)
|
for (int i = 0; i < 100; ++i)
|
||||||
async_file->info("Async message #{}", i);
|
async_file->info("Async message #{}{}", i);
|
||||||
}
|
}
|
||||||
|
|
||||||
//syslog example (linux/osx only)
|
//syslog example (linux/osx only)
|
||||||
@ -127,3 +128,15 @@ void user_defined_example()
|
|||||||
spd::get("console")->info("user defined type: {}", my_type { 14 });
|
spd::get("console")->info("user defined type: {}", my_type { 14 });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
//custom error handler
|
||||||
|
//
|
||||||
|
void err_handler_example()
|
||||||
|
{
|
||||||
|
//can be set globaly or per logger(logger->set_error_handler(..))
|
||||||
|
spdlog::set_error_handler([](const std::string& msg) {
|
||||||
|
std::cerr << "my err handler: " << msg << std::endl;
|
||||||
|
});
|
||||||
|
spd::get("console")->info("some invalid message to trigger an error {}{}{}{}", 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ -11,6 +11,8 @@
|
|||||||
#include <memory>
|
#include <memory>
|
||||||
#include <atomic>
|
#include <atomic>
|
||||||
#include <exception>
|
#include <exception>
|
||||||
|
#include<functional>
|
||||||
|
|
||||||
#if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES)
|
#if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES)
|
||||||
#include <codecvt>
|
#include <codecvt>
|
||||||
#include <locale>
|
#include <locale>
|
||||||
@ -58,6 +60,7 @@ using level_t = details::null_atomic_int;
|
|||||||
using level_t = std::atomic_int;
|
using level_t = std::atomic_int;
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
using log_err_handler = std::function<void(const std::string &err_msg)>;
|
||||||
|
|
||||||
//Log level enum
|
//Log level enum
|
||||||
namespace level
|
namespace level
|
||||||
|
@ -120,6 +120,7 @@ public:
|
|||||||
async_log_helper(formatter_ptr formatter,
|
async_log_helper(formatter_ptr formatter,
|
||||||
const std::vector<sink_ptr>& sinks,
|
const std::vector<sink_ptr>& sinks,
|
||||||
size_t queue_size,
|
size_t queue_size,
|
||||||
|
const log_err_handler err_handler,
|
||||||
const async_overflow_policy overflow_policy = async_overflow_policy::block_retry,
|
const async_overflow_policy overflow_policy = async_overflow_policy::block_retry,
|
||||||
const std::function<void()>& worker_warmup_cb = nullptr,
|
const std::function<void()>& worker_warmup_cb = nullptr,
|
||||||
const std::chrono::milliseconds& flush_interval_ms = std::chrono::milliseconds::zero(),
|
const std::chrono::milliseconds& flush_interval_ms = std::chrono::milliseconds::zero(),
|
||||||
@ -142,14 +143,13 @@ private:
|
|||||||
// queue of messages to log
|
// queue of messages to log
|
||||||
q_type _q;
|
q_type _q;
|
||||||
|
|
||||||
|
log_err_handler _err_handler;
|
||||||
|
|
||||||
bool _flush_requested;
|
bool _flush_requested;
|
||||||
|
|
||||||
bool _terminate_requested;
|
bool _terminate_requested;
|
||||||
|
|
||||||
|
|
||||||
// last exception thrown from the worker thread
|
|
||||||
std::shared_ptr<spdlog_ex> _last_workerthread_ex;
|
|
||||||
|
|
||||||
// overflow policy
|
// overflow policy
|
||||||
const async_overflow_policy _overflow_policy;
|
const async_overflow_policy _overflow_policy;
|
||||||
|
|
||||||
@ -167,9 +167,6 @@ private:
|
|||||||
|
|
||||||
void push_msg(async_msg&& new_msg);
|
void push_msg(async_msg&& new_msg);
|
||||||
|
|
||||||
// throw last worker thread exception or if worker thread is not active
|
|
||||||
void throw_if_bad_worker();
|
|
||||||
|
|
||||||
// worker thread main loop
|
// worker thread main loop
|
||||||
void worker_loop();
|
void worker_loop();
|
||||||
|
|
||||||
@ -193,6 +190,7 @@ inline spdlog::details::async_log_helper::async_log_helper(
|
|||||||
formatter_ptr formatter,
|
formatter_ptr formatter,
|
||||||
const std::vector<sink_ptr>& sinks,
|
const std::vector<sink_ptr>& sinks,
|
||||||
size_t queue_size,
|
size_t queue_size,
|
||||||
|
log_err_handler err_handler,
|
||||||
const async_overflow_policy overflow_policy,
|
const async_overflow_policy overflow_policy,
|
||||||
const std::function<void()>& worker_warmup_cb,
|
const std::function<void()>& worker_warmup_cb,
|
||||||
const std::chrono::milliseconds& flush_interval_ms,
|
const std::chrono::milliseconds& flush_interval_ms,
|
||||||
@ -200,6 +198,7 @@ inline spdlog::details::async_log_helper::async_log_helper(
|
|||||||
_formatter(formatter),
|
_formatter(formatter),
|
||||||
_sinks(sinks),
|
_sinks(sinks),
|
||||||
_q(queue_size),
|
_q(queue_size),
|
||||||
|
_err_handler(err_handler),
|
||||||
_flush_requested(false),
|
_flush_requested(false),
|
||||||
_terminate_requested(false),
|
_terminate_requested(false),
|
||||||
_overflow_policy(overflow_policy),
|
_overflow_policy(overflow_policy),
|
||||||
@ -233,7 +232,6 @@ inline void spdlog::details::async_log_helper::log(const details::log_msg& msg)
|
|||||||
|
|
||||||
inline void spdlog::details::async_log_helper::push_msg(details::async_log_helper::async_msg&& new_msg)
|
inline void spdlog::details::async_log_helper::push_msg(details::async_log_helper::async_msg&& new_msg)
|
||||||
{
|
{
|
||||||
throw_if_bad_worker();
|
|
||||||
if (!_q.enqueue(std::move(new_msg)) && _overflow_policy != async_overflow_policy::discard_log_msg)
|
if (!_q.enqueue(std::move(new_msg)) && _overflow_policy != async_overflow_policy::discard_log_msg)
|
||||||
{
|
{
|
||||||
auto last_op_time = details::os::now();
|
auto last_op_time = details::os::now();
|
||||||
@ -263,13 +261,11 @@ inline void spdlog::details::async_log_helper::worker_loop()
|
|||||||
while(process_next_msg(last_pop, last_flush));
|
while(process_next_msg(last_pop, last_flush));
|
||||||
if (_worker_teardown_cb) _worker_teardown_cb();
|
if (_worker_teardown_cb) _worker_teardown_cb();
|
||||||
}
|
}
|
||||||
catch (const std::exception& ex)
|
catch (const std::exception &ex) {
|
||||||
{
|
_err_handler(ex.what());
|
||||||
_last_workerthread_ex = std::make_shared<spdlog_ex>(std::string("async_logger worker thread exception: ") + ex.what());
|
|
||||||
}
|
}
|
||||||
catch (...)
|
catch (...) {
|
||||||
{
|
_err_handler("Unknown exception");
|
||||||
_last_workerthread_ex = std::make_shared<spdlog_ex>("async_logger worker thread exception");
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -362,15 +358,6 @@ inline void spdlog::details::async_log_helper::sleep_or_yield(const spdlog::log_
|
|||||||
return sleep_for(milliseconds(200));
|
return sleep_for(milliseconds(200));
|
||||||
}
|
}
|
||||||
|
|
||||||
// throw if the worker thread threw an exception or not active
|
|
||||||
inline void spdlog::details::async_log_helper::throw_if_bad_worker()
|
|
||||||
{
|
|
||||||
if (_last_workerthread_ex)
|
|
||||||
{
|
|
||||||
auto ex = std::move(_last_workerthread_ex);
|
|
||||||
throw *ex;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@ -26,7 +26,7 @@ inline spdlog::async_logger::async_logger(const std::string& logger_name,
|
|||||||
const std::chrono::milliseconds& flush_interval_ms,
|
const std::chrono::milliseconds& flush_interval_ms,
|
||||||
const std::function<void()>& worker_teardown_cb) :
|
const std::function<void()>& worker_teardown_cb) :
|
||||||
logger(logger_name, begin, end),
|
logger(logger_name, begin, end),
|
||||||
_async_log_helper(new details::async_log_helper(_formatter, _sinks, queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb))
|
_async_log_helper(new details::async_log_helper(_formatter, _sinks, queue_size, _err_handler, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb))
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -73,5 +73,14 @@ inline void spdlog::async_logger::_set_pattern(const std::string& pattern)
|
|||||||
|
|
||||||
inline void spdlog::async_logger::_sink_it(details::log_msg& msg)
|
inline void spdlog::async_logger::_sink_it(details::log_msg& msg)
|
||||||
{
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
_async_log_helper->log(msg);
|
_async_log_helper->log(msg);
|
||||||
|
}
|
||||||
|
catch (const std::exception &ex) {
|
||||||
|
_err_handler(ex.what());
|
||||||
|
}
|
||||||
|
catch (...) {
|
||||||
|
_err_handler("Unknown exception");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -6,35 +6,39 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <spdlog/logger.h>
|
#include <spdlog/logger.h>
|
||||||
|
#include <spdlog/sinks/stdout_sinks.h>
|
||||||
|
|
||||||
#include <memory>
|
#include <memory>
|
||||||
#include <string>
|
#include <string>
|
||||||
|
|
||||||
|
|
||||||
// create logger with given name, sinks and the default pattern formatter
|
// create logger with given name, sinks and the default pattern formatter
|
||||||
// all other ctors will call this one
|
// all other ctors will call this one
|
||||||
template<class It>
|
template<class It>
|
||||||
inline spdlog::logger::logger(const std::string& logger_name, const It& begin, const It& end) :
|
inline spdlog::logger::logger(const std::string& logger_name, const It& begin, const It& end):
|
||||||
_name(logger_name),
|
_name(logger_name),
|
||||||
_sinks(begin, end),
|
_sinks(begin, end),
|
||||||
_formatter(std::make_shared<pattern_formatter>("%+"))
|
_formatter(std::make_shared<pattern_formatter>("%+"))
|
||||||
{
|
{
|
||||||
|
|
||||||
// no support under vs2013 for member initialization for std::atomic
|
|
||||||
_level = level::info;
|
_level = level::info;
|
||||||
_flush_level = level::off;
|
_flush_level = level::off;
|
||||||
|
_last_err_time = 0;
|
||||||
|
_err_handler = [this](const std::string &msg) { this->_default_err_handler(msg);};
|
||||||
}
|
}
|
||||||
|
|
||||||
// ctor with sinks as init list
|
// ctor with sinks as init list
|
||||||
inline spdlog::logger::logger(const std::string& logger_name, sinks_init_list sinks_list) :
|
inline spdlog::logger::logger(const std::string& logger_name, sinks_init_list sinks_list):
|
||||||
logger(logger_name, sinks_list.begin(), sinks_list.end()) {}
|
logger(logger_name, sinks_list.begin(), sinks_list.end())
|
||||||
|
{}
|
||||||
|
|
||||||
|
|
||||||
// ctor with single sink
|
// ctor with single sink
|
||||||
inline spdlog::logger::logger(const std::string& logger_name, spdlog::sink_ptr single_sink) :
|
inline spdlog::logger::logger(const std::string& logger_name, spdlog::sink_ptr single_sink):
|
||||||
logger(logger_name,
|
logger(logger_name,
|
||||||
{
|
{
|
||||||
single_sink
|
single_sink
|
||||||
}) {}
|
})
|
||||||
|
{}
|
||||||
|
|
||||||
|
|
||||||
inline spdlog::logger::~logger() = default;
|
inline spdlog::logger::~logger() = default;
|
||||||
@ -56,28 +60,34 @@ inline void spdlog::logger::log(level::level_enum lvl, const char* fmt, const Ar
|
|||||||
{
|
{
|
||||||
if (!should_log(lvl)) return;
|
if (!should_log(lvl)) return;
|
||||||
|
|
||||||
|
try {
|
||||||
details::log_msg log_msg(&_name, lvl);
|
details::log_msg log_msg(&_name, lvl);
|
||||||
try
|
|
||||||
{
|
|
||||||
log_msg.raw.write(fmt, args...);
|
log_msg.raw.write(fmt, args...);
|
||||||
}
|
|
||||||
catch (fmt::FormatError &ex)
|
|
||||||
{
|
|
||||||
throw spdlog::spdlog_ex(std::string("format error in \"") + fmt + "\": " + ex.what());
|
|
||||||
}
|
|
||||||
|
|
||||||
_sink_it(log_msg);
|
_sink_it(log_msg);
|
||||||
|
}
|
||||||
|
catch (const std::exception &ex) {
|
||||||
|
_err_handler(ex.what());
|
||||||
|
}
|
||||||
|
catch (...) {
|
||||||
|
_err_handler("Unknown exception");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
template <typename... Args>
|
template <typename... Args>
|
||||||
inline void spdlog::logger::log(level::level_enum lvl, const char* msg)
|
inline void spdlog::logger::log(level::level_enum lvl, const char* msg)
|
||||||
{
|
{
|
||||||
if (!should_log(lvl)) return;
|
if (!should_log(lvl)) return;
|
||||||
|
try {
|
||||||
details::log_msg log_msg(&_name, lvl);
|
details::log_msg log_msg(&_name, lvl);
|
||||||
log_msg.raw << msg;
|
log_msg.raw << msg;
|
||||||
_sink_it(log_msg);
|
_sink_it(log_msg);
|
||||||
|
}
|
||||||
|
catch (const std::exception &ex) {
|
||||||
|
_err_handler(ex.what());
|
||||||
|
}
|
||||||
|
catch (...) {
|
||||||
|
_err_handler("Unknown exception");
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -85,11 +95,17 @@ template<typename T>
|
|||||||
inline void spdlog::logger::log(level::level_enum lvl, const T& msg)
|
inline void spdlog::logger::log(level::level_enum lvl, const T& msg)
|
||||||
{
|
{
|
||||||
if (!should_log(lvl)) return;
|
if (!should_log(lvl)) return;
|
||||||
|
try {
|
||||||
details::log_msg log_msg(&_name, lvl);
|
details::log_msg log_msg(&_name, lvl);
|
||||||
log_msg.raw << msg;
|
log_msg.raw << msg;
|
||||||
_sink_it(log_msg);
|
_sink_it(log_msg);
|
||||||
|
}
|
||||||
|
catch (const std::exception &ex) {
|
||||||
|
_err_handler(ex.what());
|
||||||
|
}
|
||||||
|
catch (...) {
|
||||||
|
_err_handler("Unknown exception");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@ -185,6 +201,17 @@ inline void spdlog::logger::set_level(spdlog::level::level_enum log_level)
|
|||||||
_level.store(log_level);
|
_level.store(log_level);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
inline void spdlog::logger::set_error_handler(spdlog::log_err_handler err_handler)
|
||||||
|
{
|
||||||
|
_err_handler = err_handler;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline spdlog::log_err_handler spdlog::logger::error_handler()
|
||||||
|
{
|
||||||
|
return _err_handler;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
inline void spdlog::logger::flush_on(level::level_enum log_level)
|
inline void spdlog::logger::flush_on(level::level_enum log_level)
|
||||||
{
|
{
|
||||||
_flush_level.store(log_level);
|
_flush_level.store(log_level);
|
||||||
@ -205,6 +232,7 @@ inline bool spdlog::logger::should_log(spdlog::level::level_enum msg_level) cons
|
|||||||
//
|
//
|
||||||
inline void spdlog::logger::_sink_it(details::log_msg& msg)
|
inline void spdlog::logger::_sink_it(details::log_msg& msg)
|
||||||
{
|
{
|
||||||
|
|
||||||
_formatter->format(msg);
|
_formatter->format(msg);
|
||||||
for (auto &sink : _sinks)
|
for (auto &sink : _sinks)
|
||||||
sink->log(msg);
|
sink->log(msg);
|
||||||
@ -228,3 +256,17 @@ inline void spdlog::logger::flush()
|
|||||||
for (auto& sink : _sinks)
|
for (auto& sink : _sinks)
|
||||||
sink->flush();
|
sink->flush();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
inline void spdlog::logger::_default_err_handler(const std::string &msg)
|
||||||
|
{
|
||||||
|
auto now = time(nullptr);
|
||||||
|
if (now - _last_err_time < 60)
|
||||||
|
return;
|
||||||
|
auto tm_time = details::os::localtime(now);
|
||||||
|
char date_buf[100];
|
||||||
|
std::strftime(date_buf, sizeof(date_buf), "%Y-%m-%d %H:%M:%S", &tm_time);
|
||||||
|
details::log_msg err_msg;
|
||||||
|
err_msg.formatted.write("[*** LOG ERROR ***] [{}] [{}] [{}]{}", name(), msg, date_buf, details::os::eol);
|
||||||
|
sinks::stderr_sink_mt::instance()->log(err_msg);
|
||||||
|
_last_err_time = now;
|
||||||
|
}
|
||||||
|
@ -21,290 +21,292 @@
|
|||||||
|
|
||||||
namespace spdlog
|
namespace spdlog
|
||||||
{
|
{
|
||||||
namespace details
|
namespace details
|
||||||
{
|
{
|
||||||
class flag_formatter
|
class flag_formatter
|
||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
virtual ~flag_formatter() {}
|
virtual ~flag_formatter()
|
||||||
|
{}
|
||||||
virtual void format(details::log_msg& msg, const std::tm& tm_time) = 0;
|
virtual void format(details::log_msg& msg, const std::tm& tm_time) = 0;
|
||||||
};
|
};
|
||||||
|
|
||||||
///////////////////////////////////////////////////////////////////////
|
///////////////////////////////////////////////////////////////////////
|
||||||
// name & level pattern appenders
|
// name & level pattern appenders
|
||||||
///////////////////////////////////////////////////////////////////////
|
///////////////////////////////////////////////////////////////////////
|
||||||
namespace
|
namespace
|
||||||
{
|
{
|
||||||
class name_formatter :public flag_formatter
|
class name_formatter:public flag_formatter
|
||||||
{
|
{
|
||||||
void format(details::log_msg& msg, const std::tm&) override
|
void format(details::log_msg& msg, const std::tm&) override
|
||||||
{
|
{
|
||||||
msg.formatted << *msg.logger_name;
|
msg.formatted << *msg.logger_name;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// log level appender
|
// log level appender
|
||||||
class level_formatter :public flag_formatter
|
class level_formatter:public flag_formatter
|
||||||
{
|
{
|
||||||
void format(details::log_msg& msg, const std::tm&) override
|
void format(details::log_msg& msg, const std::tm&) override
|
||||||
{
|
{
|
||||||
msg.formatted << level::to_str(msg.level);
|
msg.formatted << level::to_str(msg.level);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// short log level appender
|
// short log level appender
|
||||||
class short_level_formatter :public flag_formatter
|
class short_level_formatter:public flag_formatter
|
||||||
{
|
{
|
||||||
void format(details::log_msg& msg, const std::tm&) override
|
void format(details::log_msg& msg, const std::tm&) override
|
||||||
{
|
{
|
||||||
msg.formatted << level::to_short_str(msg.level);
|
msg.formatted << level::to_short_str(msg.level);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
///////////////////////////////////////////////////////////////////////
|
///////////////////////////////////////////////////////////////////////
|
||||||
// Date time pattern appenders
|
// Date time pattern appenders
|
||||||
///////////////////////////////////////////////////////////////////////
|
///////////////////////////////////////////////////////////////////////
|
||||||
|
|
||||||
static const char* ampm(const tm& t)
|
static const char* ampm(const tm& t)
|
||||||
{
|
{
|
||||||
return t.tm_hour >= 12 ? "PM" : "AM";
|
return t.tm_hour >= 12 ? "PM" : "AM";
|
||||||
}
|
}
|
||||||
|
|
||||||
static int to12h(const tm& t)
|
static int to12h(const tm& t)
|
||||||
{
|
{
|
||||||
return t.tm_hour > 12 ? t.tm_hour - 12 : t.tm_hour;
|
return t.tm_hour > 12 ? t.tm_hour - 12 : t.tm_hour;
|
||||||
}
|
}
|
||||||
|
|
||||||
//Abbreviated weekday name
|
//Abbreviated weekday name
|
||||||
static const std::string days[] { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
|
static const std::string days[]{ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
|
||||||
class a_formatter :public flag_formatter
|
class a_formatter:public flag_formatter
|
||||||
{
|
{
|
||||||
void format(details::log_msg& msg, const std::tm& tm_time) override
|
void format(details::log_msg& msg, const std::tm& tm_time) override
|
||||||
{
|
{
|
||||||
msg.formatted << days[tm_time.tm_wday];
|
msg.formatted << days[tm_time.tm_wday];
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
//Full weekday name
|
//Full weekday name
|
||||||
static const std::string full_days[] { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
|
static const std::string full_days[]{ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
|
||||||
class A_formatter :public flag_formatter
|
class A_formatter:public flag_formatter
|
||||||
{
|
{
|
||||||
void format(details::log_msg& msg, const std::tm& tm_time) override
|
void format(details::log_msg& msg, const std::tm& tm_time) override
|
||||||
{
|
{
|
||||||
msg.formatted << full_days[tm_time.tm_wday];
|
msg.formatted << full_days[tm_time.tm_wday];
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
//Abbreviated month
|
//Abbreviated month
|
||||||
static const std::string months[] { "Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec" };
|
static const std::string months[]{ "Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec" };
|
||||||
class b_formatter :public flag_formatter
|
class b_formatter:public flag_formatter
|
||||||
{
|
{
|
||||||
void format(details::log_msg& msg, const std::tm& tm_time) override
|
void format(details::log_msg& msg, const std::tm& tm_time) override
|
||||||
{
|
{
|
||||||
msg.formatted<< months[tm_time.tm_mon];
|
msg.formatted << months[tm_time.tm_mon];
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
//Full month name
|
//Full month name
|
||||||
static const std::string full_months[] { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
|
static const std::string full_months[]{ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
|
||||||
class B_formatter :public flag_formatter
|
class B_formatter:public flag_formatter
|
||||||
{
|
{
|
||||||
void format(details::log_msg& msg, const std::tm& tm_time) override
|
void format(details::log_msg& msg, const std::tm& tm_time) override
|
||||||
{
|
{
|
||||||
msg.formatted << full_months[tm_time.tm_mon];
|
msg.formatted << full_months[tm_time.tm_mon];
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
//write 2 ints seperated by sep with padding of 2
|
//write 2 ints seperated by sep with padding of 2
|
||||||
static fmt::MemoryWriter& pad_n_join(fmt::MemoryWriter& w, int v1, int v2, char sep)
|
static fmt::MemoryWriter& pad_n_join(fmt::MemoryWriter& w, int v1, int v2, char sep)
|
||||||
{
|
{
|
||||||
w << fmt::pad(v1, 2, '0') << sep << fmt::pad(v2, 2, '0');
|
w << fmt::pad(v1, 2, '0') << sep << fmt::pad(v2, 2, '0');
|
||||||
return w;
|
return w;
|
||||||
}
|
}
|
||||||
|
|
||||||
//write 3 ints seperated by sep with padding of 2
|
//write 3 ints seperated by sep with padding of 2
|
||||||
static fmt::MemoryWriter& pad_n_join(fmt::MemoryWriter& w, int v1, int v2, int v3, char sep)
|
static fmt::MemoryWriter& pad_n_join(fmt::MemoryWriter& w, int v1, int v2, int v3, char sep)
|
||||||
{
|
{
|
||||||
w << fmt::pad(v1, 2, '0') << sep << fmt::pad(v2, 2, '0') << sep << fmt::pad(v3, 2, '0');
|
w << fmt::pad(v1, 2, '0') << sep << fmt::pad(v2, 2, '0') << sep << fmt::pad(v3, 2, '0');
|
||||||
return w;
|
return w;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
//Date and time representation (Thu Aug 23 15:35:46 2014)
|
//Date and time representation (Thu Aug 23 15:35:46 2014)
|
||||||
class c_formatter :public flag_formatter
|
class c_formatter:public flag_formatter
|
||||||
{
|
{
|
||||||
void format(details::log_msg& msg, const std::tm& tm_time) override
|
void format(details::log_msg& msg, const std::tm& tm_time) override
|
||||||
{
|
{
|
||||||
msg.formatted << days[tm_time.tm_wday] << ' ' << months[tm_time.tm_mon] << ' ' << tm_time.tm_mday << ' ';
|
msg.formatted << days[tm_time.tm_wday] << ' ' << months[tm_time.tm_mon] << ' ' << tm_time.tm_mday << ' ';
|
||||||
pad_n_join(msg.formatted, tm_time.tm_hour, tm_time.tm_min, tm_time.tm_sec, ':') << ' ' << tm_time.tm_year + 1900;
|
pad_n_join(msg.formatted, tm_time.tm_hour, tm_time.tm_min, tm_time.tm_sec, ':') << ' ' << tm_time.tm_year + 1900;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
// year - 2 digit
|
// year - 2 digit
|
||||||
class C_formatter :public flag_formatter
|
class C_formatter:public flag_formatter
|
||||||
{
|
{
|
||||||
void format(details::log_msg& msg, const std::tm& tm_time) override
|
void format(details::log_msg& msg, const std::tm& tm_time) override
|
||||||
{
|
{
|
||||||
msg.formatted << fmt::pad(tm_time.tm_year % 100, 2, '0');
|
msg.formatted << fmt::pad(tm_time.tm_year % 100, 2, '0');
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
// Short MM/DD/YY date, equivalent to %m/%d/%y 08/23/01
|
// Short MM/DD/YY date, equivalent to %m/%d/%y 08/23/01
|
||||||
class D_formatter :public flag_formatter
|
class D_formatter:public flag_formatter
|
||||||
{
|
{
|
||||||
void format(details::log_msg& msg, const std::tm& tm_time) override
|
void format(details::log_msg& msg, const std::tm& tm_time) override
|
||||||
{
|
{
|
||||||
pad_n_join(msg.formatted, tm_time.tm_mon + 1, tm_time.tm_mday, tm_time.tm_year % 100, '/');
|
pad_n_join(msg.formatted, tm_time.tm_mon + 1, tm_time.tm_mday, tm_time.tm_year % 100, '/');
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
// year - 4 digit
|
// year - 4 digit
|
||||||
class Y_formatter :public flag_formatter
|
class Y_formatter:public flag_formatter
|
||||||
{
|
{
|
||||||
void format(details::log_msg& msg, const std::tm& tm_time) override
|
void format(details::log_msg& msg, const std::tm& tm_time) override
|
||||||
{
|
{
|
||||||
msg.formatted << tm_time.tm_year + 1900;
|
msg.formatted << tm_time.tm_year + 1900;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// month 1-12
|
// month 1-12
|
||||||
class m_formatter :public flag_formatter
|
class m_formatter:public flag_formatter
|
||||||
{
|
{
|
||||||
void format(details::log_msg& msg, const std::tm& tm_time) override
|
void format(details::log_msg& msg, const std::tm& tm_time) override
|
||||||
{
|
{
|
||||||
msg.formatted << fmt::pad(tm_time.tm_mon + 1, 2, '0');
|
msg.formatted << fmt::pad(tm_time.tm_mon + 1, 2, '0');
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// day of month 1-31
|
// day of month 1-31
|
||||||
class d_formatter :public flag_formatter
|
class d_formatter:public flag_formatter
|
||||||
{
|
{
|
||||||
void format(details::log_msg& msg, const std::tm& tm_time) override
|
void format(details::log_msg& msg, const std::tm& tm_time) override
|
||||||
{
|
{
|
||||||
msg.formatted << fmt::pad(tm_time.tm_mday, 2, '0');
|
msg.formatted << fmt::pad(tm_time.tm_mday, 2, '0');
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// hours in 24 format 0-23
|
// hours in 24 format 0-23
|
||||||
class H_formatter :public flag_formatter
|
class H_formatter:public flag_formatter
|
||||||
{
|
{
|
||||||
void format(details::log_msg& msg, const std::tm& tm_time) override
|
void format(details::log_msg& msg, const std::tm& tm_time) override
|
||||||
{
|
{
|
||||||
msg.formatted << fmt::pad(tm_time.tm_hour, 2, '0');
|
msg.formatted << fmt::pad(tm_time.tm_hour, 2, '0');
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// hours in 12 format 1-12
|
// hours in 12 format 1-12
|
||||||
class I_formatter :public flag_formatter
|
class I_formatter:public flag_formatter
|
||||||
{
|
{
|
||||||
void format(details::log_msg& msg, const std::tm& tm_time) override
|
void format(details::log_msg& msg, const std::tm& tm_time) override
|
||||||
{
|
{
|
||||||
msg.formatted << fmt::pad(to12h(tm_time), 2, '0');
|
msg.formatted << fmt::pad(to12h(tm_time), 2, '0');
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// minutes 0-59
|
// minutes 0-59
|
||||||
class M_formatter :public flag_formatter
|
class M_formatter:public flag_formatter
|
||||||
{
|
{
|
||||||
void format(details::log_msg& msg, const std::tm& tm_time) override
|
void format(details::log_msg& msg, const std::tm& tm_time) override
|
||||||
{
|
{
|
||||||
msg.formatted << fmt::pad(tm_time.tm_min, 2, '0');
|
msg.formatted << fmt::pad(tm_time.tm_min, 2, '0');
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// seconds 0-59
|
// seconds 0-59
|
||||||
class S_formatter :public flag_formatter
|
class S_formatter:public flag_formatter
|
||||||
{
|
{
|
||||||
void format(details::log_msg& msg, const std::tm& tm_time) override
|
void format(details::log_msg& msg, const std::tm& tm_time) override
|
||||||
{
|
{
|
||||||
msg.formatted << fmt::pad(tm_time.tm_sec, 2, '0');
|
msg.formatted << fmt::pad(tm_time.tm_sec, 2, '0');
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// milliseconds
|
// milliseconds
|
||||||
class e_formatter :public flag_formatter
|
class e_formatter:public flag_formatter
|
||||||
{
|
{
|
||||||
void format(details::log_msg& msg, const std::tm&) override
|
void format(details::log_msg& msg, const std::tm&) override
|
||||||
{
|
{
|
||||||
auto duration = msg.time.time_since_epoch();
|
auto duration = msg.time.time_since_epoch();
|
||||||
auto millis = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count() % 1000;
|
auto millis = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count() % 1000;
|
||||||
msg.formatted << fmt::pad(static_cast<int>(millis), 3, '0');
|
msg.formatted << fmt::pad(static_cast<int>(millis), 3, '0');
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// microseconds
|
// microseconds
|
||||||
class f_formatter :public flag_formatter
|
class f_formatter:public flag_formatter
|
||||||
{
|
{
|
||||||
void format(details::log_msg& msg, const std::tm&) override
|
void format(details::log_msg& msg, const std::tm&) override
|
||||||
{
|
{
|
||||||
auto duration = msg.time.time_since_epoch();
|
auto duration = msg.time.time_since_epoch();
|
||||||
auto micros = std::chrono::duration_cast<std::chrono::microseconds>(duration).count() % 1000000;
|
auto micros = std::chrono::duration_cast<std::chrono::microseconds>(duration).count() % 1000000;
|
||||||
msg.formatted << fmt::pad(static_cast<int>(micros), 6, '0');
|
msg.formatted << fmt::pad(static_cast<int>(micros), 6, '0');
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// nanoseconds
|
// nanoseconds
|
||||||
class F_formatter :public flag_formatter
|
class F_formatter:public flag_formatter
|
||||||
{
|
{
|
||||||
void format(details::log_msg& msg, const std::tm&) override
|
void format(details::log_msg& msg, const std::tm&) override
|
||||||
{
|
{
|
||||||
auto duration = msg.time.time_since_epoch();
|
auto duration = msg.time.time_since_epoch();
|
||||||
auto ns = std::chrono::duration_cast<std::chrono::nanoseconds>(duration).count() % 1000000000;
|
auto ns = std::chrono::duration_cast<std::chrono::nanoseconds>(duration).count() % 1000000000;
|
||||||
msg.formatted << fmt::pad(static_cast<int>(ns), 9, '0');
|
msg.formatted << fmt::pad(static_cast<int>(ns), 9, '0');
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// AM/PM
|
// AM/PM
|
||||||
class p_formatter :public flag_formatter
|
class p_formatter:public flag_formatter
|
||||||
{
|
{
|
||||||
void format(details::log_msg& msg, const std::tm& tm_time) override
|
void format(details::log_msg& msg, const std::tm& tm_time) override
|
||||||
{
|
{
|
||||||
msg.formatted << ampm(tm_time);
|
msg.formatted << ampm(tm_time);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
// 12 hour clock 02:55:02 pm
|
// 12 hour clock 02:55:02 pm
|
||||||
class r_formatter :public flag_formatter
|
class r_formatter:public flag_formatter
|
||||||
{
|
{
|
||||||
void format(details::log_msg& msg, const std::tm& tm_time) override
|
void format(details::log_msg& msg, const std::tm& tm_time) override
|
||||||
{
|
{
|
||||||
pad_n_join(msg.formatted, to12h(tm_time), tm_time.tm_min, tm_time.tm_sec, ':') << ' ' << ampm(tm_time);
|
pad_n_join(msg.formatted, to12h(tm_time), tm_time.tm_min, tm_time.tm_sec, ':') << ' ' << ampm(tm_time);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// 24-hour HH:MM time, equivalent to %H:%M
|
// 24-hour HH:MM time, equivalent to %H:%M
|
||||||
class R_formatter :public flag_formatter
|
class R_formatter:public flag_formatter
|
||||||
{
|
{
|
||||||
void format(details::log_msg& msg, const std::tm& tm_time) override
|
void format(details::log_msg& msg, const std::tm& tm_time) override
|
||||||
{
|
{
|
||||||
pad_n_join(msg.formatted, tm_time.tm_hour, tm_time.tm_min, ':');
|
pad_n_join(msg.formatted, tm_time.tm_hour, tm_time.tm_min, ':');
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// ISO 8601 time format (HH:MM:SS), equivalent to %H:%M:%S
|
// ISO 8601 time format (HH:MM:SS), equivalent to %H:%M:%S
|
||||||
class T_formatter :public flag_formatter
|
class T_formatter:public flag_formatter
|
||||||
{
|
{
|
||||||
void format(details::log_msg& msg, const std::tm& tm_time) override
|
void format(details::log_msg& msg, const std::tm& tm_time) override
|
||||||
{
|
{
|
||||||
pad_n_join(msg.formatted, tm_time.tm_hour, tm_time.tm_min, tm_time.tm_sec, ':');
|
pad_n_join(msg.formatted, tm_time.tm_hour, tm_time.tm_min, tm_time.tm_sec, ':');
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
// ISO 8601 offset from UTC in timezone (+-HH:MM)
|
// ISO 8601 offset from UTC in timezone (+-HH:MM)
|
||||||
class z_formatter :public flag_formatter
|
class z_formatter:public flag_formatter
|
||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
const std::chrono::seconds cache_refresh = std::chrono::seconds(5);
|
const std::chrono::seconds cache_refresh = std::chrono::seconds(5);
|
||||||
|
|
||||||
z_formatter() :_last_update(std::chrono::seconds(0)) {}
|
z_formatter():_last_update(std::chrono::seconds(0))
|
||||||
|
{}
|
||||||
z_formatter(const z_formatter&) = delete;
|
z_formatter(const z_formatter&) = delete;
|
||||||
z_formatter& operator=(const z_formatter&) = delete;
|
z_formatter& operator=(const z_formatter&) = delete;
|
||||||
|
|
||||||
@ -326,7 +328,7 @@ public:
|
|||||||
}
|
}
|
||||||
pad_n_join(msg.formatted, h, m, ':');
|
pad_n_join(msg.formatted, h, m, ':');
|
||||||
}
|
}
|
||||||
private:
|
private:
|
||||||
log_clock::time_point _last_update;
|
log_clock::time_point _last_update;
|
||||||
int _offset_minutes;
|
int _offset_minutes;
|
||||||
std::mutex _mutex;
|
std::mutex _mutex;
|
||||||
@ -335,53 +337,52 @@ private:
|
|||||||
{
|
{
|
||||||
using namespace std::chrono;
|
using namespace std::chrono;
|
||||||
std::lock_guard<std::mutex> l(_mutex);
|
std::lock_guard<std::mutex> l(_mutex);
|
||||||
if (msg.time - _last_update >= cache_refresh)
|
if (msg.time - _last_update >= cache_refresh) {
|
||||||
{
|
|
||||||
_offset_minutes = os::utc_minutes_offset(tm_time);
|
_offset_minutes = os::utc_minutes_offset(tm_time);
|
||||||
_last_update = msg.time;
|
_last_update = msg.time;
|
||||||
}
|
}
|
||||||
return _offset_minutes;
|
return _offset_minutes;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
//Thread id
|
//Thread id
|
||||||
class t_formatter :public flag_formatter
|
class t_formatter:public flag_formatter
|
||||||
{
|
{
|
||||||
void format(details::log_msg& msg, const std::tm&) override
|
void format(details::log_msg& msg, const std::tm&) override
|
||||||
{
|
{
|
||||||
msg.formatted << msg.thread_id;
|
msg.formatted << msg.thread_id;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
class v_formatter :public flag_formatter
|
class v_formatter:public flag_formatter
|
||||||
{
|
{
|
||||||
void format(details::log_msg& msg, const std::tm&) override
|
void format(details::log_msg& msg, const std::tm&) override
|
||||||
{
|
{
|
||||||
msg.formatted << fmt::StringRef(msg.raw.data(), msg.raw.size());
|
msg.formatted << fmt::StringRef(msg.raw.data(), msg.raw.size());
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
class ch_formatter :public flag_formatter
|
class ch_formatter:public flag_formatter
|
||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
explicit ch_formatter(char ch) : _ch(ch)
|
explicit ch_formatter(char ch): _ch(ch)
|
||||||
{}
|
{}
|
||||||
void format(details::log_msg& msg, const std::tm&) override
|
void format(details::log_msg& msg, const std::tm&) override
|
||||||
{
|
{
|
||||||
msg.formatted << _ch;
|
msg.formatted << _ch;
|
||||||
}
|
}
|
||||||
private:
|
private:
|
||||||
char _ch;
|
char _ch;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
//aggregate user chars to display as is
|
//aggregate user chars to display as is
|
||||||
class aggregate_formatter :public flag_formatter
|
class aggregate_formatter:public flag_formatter
|
||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
aggregate_formatter()
|
aggregate_formatter()
|
||||||
{}
|
{}
|
||||||
void add_ch(char ch)
|
void add_ch(char ch)
|
||||||
@ -392,14 +393,14 @@ public:
|
|||||||
{
|
{
|
||||||
msg.formatted << _str;
|
msg.formatted << _str;
|
||||||
}
|
}
|
||||||
private:
|
private:
|
||||||
std::string _str;
|
std::string _str;
|
||||||
};
|
};
|
||||||
|
|
||||||
// Full info formatter
|
// Full info formatter
|
||||||
// pattern: [%Y-%m-%d %H:%M:%S.%e] [%n] [%l] %v
|
// pattern: [%Y-%m-%d %H:%M:%S.%e] [%n] [%l] %v
|
||||||
class full_formatter :public flag_formatter
|
class full_formatter:public flag_formatter
|
||||||
{
|
{
|
||||||
void format(details::log_msg& msg, const std::tm& tm_time) override
|
void format(details::log_msg& msg, const std::tm& tm_time) override
|
||||||
{
|
{
|
||||||
#ifndef SPDLOG_NO_DATETIME
|
#ifndef SPDLOG_NO_DATETIME
|
||||||
@ -429,7 +430,7 @@ class full_formatter :public flag_formatter
|
|||||||
<< fmt::pad(static_cast<unsigned int>(tm_time.tm_sec), 2, '0') << '.'
|
<< fmt::pad(static_cast<unsigned int>(tm_time.tm_sec), 2, '0') << '.'
|
||||||
<< fmt::pad(static_cast<unsigned int>(millis), 3, '0') << "] ";
|
<< fmt::pad(static_cast<unsigned int>(millis), 3, '0') << "] ";
|
||||||
|
|
||||||
//no datetime needed
|
//no datetime needed
|
||||||
#else
|
#else
|
||||||
(void)tm_time;
|
(void)tm_time;
|
||||||
#endif
|
#endif
|
||||||
@ -441,9 +442,9 @@ class full_formatter :public flag_formatter
|
|||||||
msg.formatted << '[' << level::to_str(msg.level) << "] ";
|
msg.formatted << '[' << level::to_str(msg.level) << "] ";
|
||||||
msg.formatted << fmt::StringRef(msg.raw.data(), msg.raw.size());
|
msg.formatted << fmt::StringRef(msg.raw.data(), msg.raw.size());
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
///////////////////////////////////////////////////////////////////////////////
|
///////////////////////////////////////////////////////////////////////////////
|
||||||
// pattern_formatter inline impl
|
// pattern_formatter inline impl
|
||||||
@ -457,10 +458,8 @@ inline void spdlog::pattern_formatter::compile_pattern(const std::string& patter
|
|||||||
{
|
{
|
||||||
auto end = pattern.end();
|
auto end = pattern.end();
|
||||||
std::unique_ptr<details::aggregate_formatter> user_chars;
|
std::unique_ptr<details::aggregate_formatter> user_chars;
|
||||||
for (auto it = pattern.begin(); it != end; ++it)
|
for (auto it = pattern.begin(); it != end; ++it) {
|
||||||
{
|
if (*it == '%') {
|
||||||
if (*it == '%')
|
|
||||||
{
|
|
||||||
if (user_chars) //append user chars found so far
|
if (user_chars) //append user chars found so far
|
||||||
_formatters.push_back(std::move(user_chars));
|
_formatters.push_back(std::move(user_chars));
|
||||||
|
|
||||||
@ -484,8 +483,7 @@ inline void spdlog::pattern_formatter::compile_pattern(const std::string& patter
|
|||||||
}
|
}
|
||||||
inline void spdlog::pattern_formatter::handle_flag(char flag)
|
inline void spdlog::pattern_formatter::handle_flag(char flag)
|
||||||
{
|
{
|
||||||
switch (flag)
|
switch (flag) {
|
||||||
{
|
|
||||||
// logger name
|
// logger name
|
||||||
case 'n':
|
case 'n':
|
||||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::name_formatter()));
|
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::name_formatter()));
|
||||||
@ -499,101 +497,101 @@ inline void spdlog::pattern_formatter::handle_flag(char flag)
|
|||||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::short_level_formatter()));
|
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::short_level_formatter()));
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case('t') :
|
case('t'):
|
||||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::t_formatter()));
|
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::t_formatter()));
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case('v') :
|
case('v'):
|
||||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::v_formatter()));
|
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::v_formatter()));
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case('a') :
|
case('a'):
|
||||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::a_formatter()));
|
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::a_formatter()));
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case('A') :
|
case('A'):
|
||||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::A_formatter()));
|
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::A_formatter()));
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case('b') :
|
case('b'):
|
||||||
case('h') :
|
case('h'):
|
||||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::b_formatter()));
|
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::b_formatter()));
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case('B') :
|
case('B'):
|
||||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::B_formatter()));
|
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::B_formatter()));
|
||||||
break;
|
break;
|
||||||
case('c') :
|
case('c'):
|
||||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::c_formatter()));
|
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::c_formatter()));
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case('C') :
|
case('C'):
|
||||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::C_formatter()));
|
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::C_formatter()));
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case('Y') :
|
case('Y'):
|
||||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::Y_formatter()));
|
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::Y_formatter()));
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case('D') :
|
case('D'):
|
||||||
case('x') :
|
case('x'):
|
||||||
|
|
||||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::D_formatter()));
|
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::D_formatter()));
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case('m') :
|
case('m'):
|
||||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::m_formatter()));
|
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::m_formatter()));
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case('d') :
|
case('d'):
|
||||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::d_formatter()));
|
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::d_formatter()));
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case('H') :
|
case('H'):
|
||||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::H_formatter()));
|
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::H_formatter()));
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case('I') :
|
case('I'):
|
||||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::I_formatter()));
|
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::I_formatter()));
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case('M') :
|
case('M'):
|
||||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::M_formatter()));
|
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::M_formatter()));
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case('S') :
|
case('S'):
|
||||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::S_formatter()));
|
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::S_formatter()));
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case('e') :
|
case('e'):
|
||||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::e_formatter()));
|
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::e_formatter()));
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case('f') :
|
case('f'):
|
||||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::f_formatter()));
|
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::f_formatter()));
|
||||||
break;
|
break;
|
||||||
case('F') :
|
case('F'):
|
||||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::F_formatter()));
|
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::F_formatter()));
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case('p') :
|
case('p'):
|
||||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::p_formatter()));
|
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::p_formatter()));
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case('r') :
|
case('r'):
|
||||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::r_formatter()));
|
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::r_formatter()));
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case('R') :
|
case('R'):
|
||||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::R_formatter()));
|
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::R_formatter()));
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case('T') :
|
case('T'):
|
||||||
case('X') :
|
case('X'):
|
||||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::T_formatter()));
|
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::T_formatter()));
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case('z') :
|
case('z'):
|
||||||
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::z_formatter()));
|
_formatters.push_back(std::unique_ptr<details::flag_formatter>(new details::z_formatter()));
|
||||||
break;
|
break;
|
||||||
|
|
||||||
@ -611,22 +609,15 @@ inline void spdlog::pattern_formatter::handle_flag(char flag)
|
|||||||
|
|
||||||
inline void spdlog::pattern_formatter::format(details::log_msg& msg)
|
inline void spdlog::pattern_formatter::format(details::log_msg& msg)
|
||||||
{
|
{
|
||||||
try
|
|
||||||
{
|
|
||||||
#ifndef SPDLOG_NO_DATETIME
|
#ifndef SPDLOG_NO_DATETIME
|
||||||
auto tm_time = details::os::localtime(log_clock::to_time_t(msg.time));
|
auto tm_time = details::os::localtime(log_clock::to_time_t(msg.time));
|
||||||
#else
|
#else
|
||||||
std::tm tm_time;
|
std::tm tm_time;
|
||||||
#endif
|
#endif
|
||||||
for (auto &f : _formatters)
|
for (auto &f : _formatters) {
|
||||||
{
|
|
||||||
f->format(msg, tm_time);
|
f->format(msg, tm_time);
|
||||||
}
|
}
|
||||||
//write eol
|
//write eol
|
||||||
msg.formatted.write(details::os::eol, details::os::eol_size);
|
msg.formatted.write(details::os::eol, details::os::eol_size);
|
||||||
}
|
|
||||||
catch(const fmt::FormatError& e)
|
|
||||||
{
|
|
||||||
throw spdlog_ex(fmt::format("formatting error while processing format string: {}", e.what()));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
@ -60,7 +60,12 @@ public:
|
|||||||
if (_formatter)
|
if (_formatter)
|
||||||
new_logger->set_formatter(_formatter);
|
new_logger->set_formatter(_formatter);
|
||||||
|
|
||||||
|
if (_err_handler)
|
||||||
|
new_logger->set_error_handler(_err_handler);
|
||||||
|
|
||||||
new_logger->set_level(_level);
|
new_logger->set_level(_level);
|
||||||
|
|
||||||
|
|
||||||
//Add to registry
|
//Add to registry
|
||||||
_loggers[logger_name] = new_logger;
|
_loggers[logger_name] = new_logger;
|
||||||
return new_logger;
|
return new_logger;
|
||||||
@ -112,6 +117,13 @@ public:
|
|||||||
_level = log_level;
|
_level = log_level;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void set_error_handler(log_err_handler handler)
|
||||||
|
{
|
||||||
|
for (auto& l : _loggers)
|
||||||
|
l.second->set_error_handler(handler);
|
||||||
|
_err_handler = handler;
|
||||||
|
}
|
||||||
|
|
||||||
void set_async_mode(size_t q_size, const async_overflow_policy overflow_policy, const std::function<void()>& worker_warmup_cb, const std::chrono::milliseconds& flush_interval_ms, const std::function<void()>& worker_teardown_cb)
|
void set_async_mode(size_t q_size, const async_overflow_policy overflow_policy, const std::function<void()>& worker_warmup_cb, const std::chrono::milliseconds& flush_interval_ms, const std::function<void()>& worker_teardown_cb)
|
||||||
{
|
{
|
||||||
std::lock_guard<Mutex> lock(_mutex);
|
std::lock_guard<Mutex> lock(_mutex);
|
||||||
@ -149,6 +161,7 @@ private:
|
|||||||
std::unordered_map <std::string, std::shared_ptr<logger>> _loggers;
|
std::unordered_map <std::string, std::shared_ptr<logger>> _loggers;
|
||||||
formatter_ptr _formatter;
|
formatter_ptr _formatter;
|
||||||
level::level_enum _level = level::info;
|
level::level_enum _level = level::info;
|
||||||
|
log_err_handler _err_handler;
|
||||||
bool _async_mode = false;
|
bool _async_mode = false;
|
||||||
size_t _async_q_size = 0;
|
size_t _async_q_size = 0;
|
||||||
async_overflow_policy _overflow_policy = async_overflow_policy::block_retry;
|
async_overflow_policy _overflow_policy = async_overflow_policy::block_retry;
|
||||||
|
@ -147,6 +147,13 @@ inline void spdlog::set_level(level::level_enum log_level)
|
|||||||
return details::registry::instance().set_level(log_level);
|
return details::registry::instance().set_level(log_level);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
inline void spdlog::set_error_handler(log_err_handler handler)
|
||||||
|
{
|
||||||
|
return details::registry::instance().set_error_handler(handler);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
inline void spdlog::set_async_mode(size_t queue_size, const async_overflow_policy overflow_policy, const std::function<void()>& worker_warmup_cb, const std::chrono::milliseconds& flush_interval_ms, const std::function<void()>& worker_teardown_cb)
|
inline void spdlog::set_async_mode(size_t queue_size, const async_overflow_policy overflow_policy, const std::function<void()>& worker_warmup_cb, const std::chrono::milliseconds& flush_interval_ms, const std::function<void()>& worker_teardown_cb)
|
||||||
{
|
{
|
||||||
|
@ -19,7 +19,6 @@
|
|||||||
#include <memory>
|
#include <memory>
|
||||||
#include <string>
|
#include <string>
|
||||||
|
|
||||||
|
|
||||||
namespace spdlog
|
namespace spdlog
|
||||||
{
|
{
|
||||||
|
|
||||||
@ -53,7 +52,6 @@ public:
|
|||||||
template <typename T> void error(const T&);
|
template <typename T> void error(const T&);
|
||||||
template <typename T> void critical(const T&);
|
template <typename T> void critical(const T&);
|
||||||
|
|
||||||
|
|
||||||
bool should_log(level::level_enum) const;
|
bool should_log(level::level_enum) const;
|
||||||
void set_level(level::level_enum);
|
void set_level(level::level_enum);
|
||||||
level::level_enum level() const;
|
level::level_enum level() const;
|
||||||
@ -61,6 +59,10 @@ public:
|
|||||||
void set_pattern(const std::string&);
|
void set_pattern(const std::string&);
|
||||||
void set_formatter(formatter_ptr);
|
void set_formatter(formatter_ptr);
|
||||||
|
|
||||||
|
// error handler
|
||||||
|
void set_error_handler(log_err_handler);
|
||||||
|
log_err_handler error_handler();
|
||||||
|
|
||||||
// automatically call flush() if message level >= log_level
|
// automatically call flush() if message level >= log_level
|
||||||
void flush_on(level::level_enum log_level);
|
void flush_on(level::level_enum log_level);
|
||||||
virtual void flush();
|
virtual void flush();
|
||||||
@ -70,11 +72,16 @@ protected:
|
|||||||
virtual void _set_pattern(const std::string&);
|
virtual void _set_pattern(const std::string&);
|
||||||
virtual void _set_formatter(formatter_ptr);
|
virtual void _set_formatter(formatter_ptr);
|
||||||
|
|
||||||
|
// default error handler: print the error to stderr with the max rate of 1 message/minute
|
||||||
|
virtual void _default_err_handler(const std::string &msg);
|
||||||
|
|
||||||
const std::string _name;
|
const std::string _name;
|
||||||
std::vector<sink_ptr> _sinks;
|
std::vector<sink_ptr> _sinks;
|
||||||
formatter_ptr _formatter;
|
formatter_ptr _formatter;
|
||||||
spdlog::level_t _level;
|
spdlog::level_t _level;
|
||||||
spdlog::level_t _flush_level;
|
spdlog::level_t _flush_level;
|
||||||
|
log_err_handler _err_handler;
|
||||||
|
std::atomic<time_t> _last_err_time;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -41,6 +41,11 @@ void set_formatter(formatter_ptr f);
|
|||||||
//
|
//
|
||||||
void set_level(level::level_enum log_level);
|
void set_level(level::level_enum log_level);
|
||||||
|
|
||||||
|
//
|
||||||
|
// Set global error handler
|
||||||
|
//
|
||||||
|
void set_error_handler(log_err_handler);
|
||||||
|
|
||||||
//
|
//
|
||||||
// Turn on async mode (off by default) and set the queue size for each async_logger.
|
// Turn on async mode (off by default) and set the queue size for each async_logger.
|
||||||
// effective only for loggers created after this call.
|
// effective only for loggers created after this call.
|
||||||
|
61
tests/errors.cpp
Normal file
61
tests/errors.cpp
Normal file
@ -0,0 +1,61 @@
|
|||||||
|
/*
|
||||||
|
* This content is released under the MIT License as specified in https://raw.githubusercontent.com/gabime/spdlog/master/LICENSE
|
||||||
|
*/
|
||||||
|
#include "includes.h"
|
||||||
|
|
||||||
|
#include<iostream>
|
||||||
|
|
||||||
|
|
||||||
|
TEST_CASE("default_error_handler", "[errors]]")
|
||||||
|
{
|
||||||
|
prepare_logdir();
|
||||||
|
std::string filename = "logs/simple_log.txt";
|
||||||
|
|
||||||
|
auto logger = spdlog::create<spdlog::sinks::simple_file_sink_mt>("logger", filename, true);
|
||||||
|
logger->set_pattern("%v");
|
||||||
|
logger->info("Test message {} {}", 1);
|
||||||
|
logger->info("Test message {}", 2);
|
||||||
|
logger->flush();
|
||||||
|
|
||||||
|
REQUIRE(file_contents(filename) == std::string("Test message 2\n"));
|
||||||
|
REQUIRE(count_lines(filename) == 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
struct custom_ex{};
|
||||||
|
TEST_CASE("custom_error_handler", "[errors]]")
|
||||||
|
{
|
||||||
|
prepare_logdir();
|
||||||
|
std::string filename = "logs/simple_log.txt";
|
||||||
|
auto logger = spdlog::create<spdlog::sinks::simple_file_sink_mt>("logger", filename, true);
|
||||||
|
logger->set_error_handler([=](const std::string& msg) {
|
||||||
|
throw custom_ex();
|
||||||
|
});
|
||||||
|
logger->info("Good message #1");
|
||||||
|
REQUIRE_THROWS_AS(logger->info("Bad format msg {} {}", "xxx"), custom_ex);
|
||||||
|
logger->info("Good message #2");
|
||||||
|
REQUIRE(count_lines(filename) == 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST_CASE("async_error_handler", "[errors]]")
|
||||||
|
{
|
||||||
|
prepare_logdir();
|
||||||
|
std::string err_msg("log failed with some msg");
|
||||||
|
spdlog::set_async_mode(128);
|
||||||
|
std::string filename = "logs/simple_async_log.txt";
|
||||||
|
{
|
||||||
|
auto logger = spdlog::create<spdlog::sinks::simple_file_sink_mt>("logger", filename, true);
|
||||||
|
logger->set_error_handler([=](const std::string& msg) {
|
||||||
|
std::ofstream ofs("logs/custom_err.txt");
|
||||||
|
if (!ofs) throw std::runtime_error("Failed open logs/custom_err.txt");
|
||||||
|
ofs << err_msg;
|
||||||
|
});
|
||||||
|
logger->info("Good message #1");
|
||||||
|
logger->info("Bad format msg {} {}", "xxx");
|
||||||
|
logger->info("Good message #2");
|
||||||
|
spdlog::drop("logger"); //force logger to drain the queue and shutdown
|
||||||
|
spdlog::set_sync_mode();
|
||||||
|
}
|
||||||
|
REQUIRE(count_lines(filename) == 2);
|
||||||
|
REQUIRE(file_contents("logs/custom_err.txt") == err_msg);
|
||||||
|
}
|
@ -49,24 +49,7 @@ TEST_CASE("log_levels", "[log_levels]")
|
|||||||
REQUIRE(log_info("Hello", spdlog::level::trace) == "Hello");
|
REQUIRE(log_info("Hello", spdlog::level::trace) == "Hello");
|
||||||
}
|
}
|
||||||
|
|
||||||
TEST_CASE("invalid_format", "[format]")
|
|
||||||
{
|
|
||||||
|
|
||||||
using namespace spdlog::sinks;
|
|
||||||
spdlog::logger null_logger("null_logger", std::make_shared<null_sink_st>());
|
|
||||||
REQUIRE_THROWS_AS(
|
|
||||||
null_logger.info("{} {}", "first"),
|
|
||||||
spdlog::spdlog_ex);
|
|
||||||
|
|
||||||
REQUIRE_THROWS_AS(
|
|
||||||
null_logger.info("{0:f}", "aads"),
|
|
||||||
spdlog::spdlog_ex);
|
|
||||||
|
|
||||||
REQUIRE_THROWS_AS(
|
|
||||||
null_logger.info("{0:kk}", 123),
|
|
||||||
spdlog::spdlog_ex);
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@ -125,6 +125,7 @@
|
|||||||
</Link>
|
</Link>
|
||||||
</ItemDefinitionGroup>
|
</ItemDefinitionGroup>
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
<ClCompile Include="errors.cpp" />
|
||||||
<ClCompile Include="file_helper.cpp" />
|
<ClCompile Include="file_helper.cpp" />
|
||||||
<ClCompile Include="file_log.cpp" />
|
<ClCompile Include="file_log.cpp" />
|
||||||
<ClCompile Include="format.cpp" />
|
<ClCompile Include="format.cpp" />
|
||||||
|
@ -33,6 +33,9 @@
|
|||||||
<ClCompile Include="utils.cpp">
|
<ClCompile Include="utils.cpp">
|
||||||
<Filter>Source Files</Filter>
|
<Filter>Source Files</Filter>
|
||||||
</ClCompile>
|
</ClCompile>
|
||||||
|
<ClCompile Include="errors.cpp">
|
||||||
|
<Filter>Source Files</Filter>
|
||||||
|
</ClCompile>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ClInclude Include="includes.h">
|
<ClInclude Include="includes.h">
|
||||||
|
Loading…
Reference in New Issue
Block a user