Compare commits

..

34 Commits

Author SHA1 Message Date
Gabi Melman
dea6bb1085 Merge pull request #2359 from tiolan/master
Revert "Merge pull request #2352 from tiolan/topic/android_buffer"
2022-05-12 23:24:55 +03:00
Timo Lange
b960d5a062 Revert "Merge pull request #2352 from tiolan/topic/android_buffer"
This reverts commit c6d0487474, reversing
changes made to a51b485637.
2022-05-06 11:54:01 +02:00
Gabi Melman
c6d0487474 Merge pull request #2352 from tiolan/topic/android_buffer
Allow modifying the used Android buffer
2022-05-03 01:44:58 +03:00
Timo Lange
7d22b689b6 use __android_log_write or __android_log_buf_write based on template parameter 2022-04-29 21:12:19 +02:00
Gabi Melman
a51b485637 Merge pull request #1210 from jimmyorourke/patch-1
Windows color file sink: Use WriteFile rather than WriteConsole
2019-09-06 07:50:15 +03:00
jimmyorourke
3a13e76bb1 Use WriteFile rather than WriteConsole to be able to use file handles or pipes 2019-09-03 14:16:39 -04:00
Gabi Melman
139c0d135f Merge pull request #1112 from thomaslewis1096/master
Added !defined(__HAIKU__) to #if for stat64 struct.
2019-06-15 22:21:00 +03:00
Thomas Lewis
cee913d76e Added __HAIKU__ to #if for stat64 struct. 2019-06-15 12:10:12 -06:00
Gabi Melman
7088644d3f Merge pull request #821 from rkanavath/compile_fix
fix build on openbsd
2018-09-04 15:32:02 +03:00
Rashad Kanavath
9ca4e3d8bc fix build on openbsd 2018-09-04 11:41:06 +02:00
Gabi Melman
f1a60eb6b1 Update INSTALL 2018-07-08 14:34:33 +03:00
Gabi Melman
96961e14ad Update INSTALL 2018-07-08 14:34:18 +03:00
Gabi Melman
c639483db0 Merge pull request #735 from jwnimmer-tri/dist_sink_reset
add remove_all_sinks method to dist_sink
2018-06-21 17:22:18 +03:00
Jeremy Nimmer
b3881b9c15 add remove_all_sinks method to dist_sink
This allows users to set exactly the sinks they want, even if other
unknown application code has added bespoke sinks in the meantime.
2018-06-13 07:42:20 -04:00
gabime
032035e72f format 2018-06-10 23:22:31 +03:00
gabime
66b5772b61 Fixed issue #720 2018-06-10 23:22:19 +03:00
gabime
faea32c9f9 simplfiy a little the use of fmt:safe_strerror 2018-06-01 16:58:07 +03:00
Gabi Melman
d78ddcee24 Merge pull request #719 from JamesReynolds/master
Closes #717
2018-06-01 16:42:45 +03:00
JamesReynolds
7bc598c9b5 Move errno code into common
errno code is no longer OS specific. Moving to common.
2018-06-01 14:32:33 +01:00
JamesReynolds
aa9012fa07 Fixes #717
This fix uses the fmt::safe_strerror instead of the underlying
strerror_r functionality. I think this is better - but I'm not
sure if there is a reason for avoiding the use of this function.
2018-06-01 12:24:06 +01:00
JamesReynolds
3fbac8e2b7 Closes #717
Failure to compile to systems that don't have a valid definition
of strerror_r.
2018-06-01 11:53:46 +01:00
Gabi Melman
d033ccc0c7 Update README.md 2018-05-30 18:26:52 +03:00
Gabi Melman
1fcc896486 Merge pull request #715 from JamesReynolds/master
Closes gabime/spdlog#74
2018-05-30 15:25:40 +03:00
Gabi Melman
4640c5cb50 Merge pull request #713 from Puasonych/master
Update step logger
2018-05-30 13:30:13 +03:00
JamesReynolds
4131347079 This closes #74 in gabime/spdlog
Support for AIX. Tested on AIX 6.1 with GCC 6.3.
2018-05-30 10:44:41 +01:00
puasonych
98b9cd38ec Update step logger 2018-05-30 13:07:43 +05:00
puasonych
877a618400 Update step logger
Fixed bugs with multithreading and added protection against data lost with insufficiently accurate setting of the maximum value of the file size
2018-05-30 12:48:56 +05:00
puasonych
eb2118c181 Update step_file_sink 2018-05-30 09:40:09 +05:00
puasonych
5c1951acec Update step_file_sink
Fixed adding a file header and adding ignoring of empty files
2018-05-25 22:20:14 +05:00
gabime
67a6eaf23e Merge branch 'master' of https://github.com/gabime/spdlog 2018-05-24 00:09:54 +03:00
gabime
f4db1c510c catch potential flush exceptions 2018-05-24 00:09:38 +03:00
Gabi Melman
2aa25109ef Merge pull request #706 from Puasonych/master
Added file header support for step_logger
2018-05-22 09:08:10 +03:00
Puasonych
bd3f8a3b92 Added file header support 2018-05-22 08:27:34 +03:00
Gabi Melman
d6b700eaf2 Update async_log_helper.h 2018-05-21 21:16:34 +03:00
15 changed files with 250 additions and 166 deletions

View File

@@ -2,9 +2,9 @@ spdlog is header only library.
Just copy the files to your build tree and use a C++11 compiler Just copy the files to your build tree and use a C++11 compiler
Tested on: Tested on:
gcc 4.8.1 and above gcc 4.8.1 or above
clang 3.5 clang 3.5 or above
Visual Studio 2013 Visual Studio 2013 or above
gcc 4.8 flags: --std==c++11 -pthread -O3 -flto -Wl,--no-as-needed gcc 4.8 flags: --std==c++11 -pthread -O3 -flto -Wl,--no-as-needed
gcc 4.9 flags: --std=c++11 -pthread -O3 -flto gcc 4.9 flags: --std=c++11 -pthread -O3 -flto

View File

@@ -20,7 +20,7 @@ Very fast, header only, C++ logging library. [![Build Status](https://travis-ci.
## Platforms ## Platforms
* Linux, FreeBSD, Solaris * Linux, FreeBSD, Solaris, AIX
* Windows (vc 2013+, cygwin) * Windows (vc 2013+, cygwin)
* Mac OSX (clang 3.5+) * Mac OSX (clang 3.5+)
* Android * Android

View File

@@ -143,11 +143,6 @@ enum class pattern_time_type
// //
// Log exception // Log exception
// //
namespace details {
namespace os {
std::string errno_str(int err_num);
}
} // namespace details
class spdlog_ex : public std::exception class spdlog_ex : public std::exception
{ {
public: public:
@@ -158,7 +153,9 @@ public:
spdlog_ex(const std::string &msg, int last_errno) spdlog_ex(const std::string &msg, int last_errno)
{ {
_msg = msg + ": " + details::os::errno_str(last_errno); fmt::MemoryWriter writer;
fmt::format_system_error(writer, last_errno, msg);
_msg = writer.str();
} }
const char *what() const SPDLOG_NOEXCEPT override const char *what() const SPDLOG_NOEXCEPT override
@@ -179,4 +176,13 @@ using filename_t = std::wstring;
using filename_t = std::string; using filename_t = std::string;
#endif #endif
#define SPDLOG_CATCH_AND_HANDLE \
catch (const std::exception &ex) \
{ \
_err_handler(ex.what()); \
} \
catch (...) \
{ \
_err_handler("Unknown exeption in logger"); \
}
} // namespace spdlog } // namespace spdlog

View File

@@ -18,22 +18,26 @@
// Create a file logger which creates new files with a specified time step and fixed file size: // Create a file logger which creates new files with a specified time step and fixed file size:
// //
// std::shared_ptr<logger> step_logger_mt(const std::string &logger_name, const filename_t &filename, unsigned seconds = 60, const // std::shared_ptr<logger> step_logger_mt(const std::string &logger_name, const filename_t &filename, unsigned seconds = 60, const
// filename_t &tmp_ext = ".tmp", unsigned max_file_size = std::numeric_limits<unsigned>::max()); std::shared_ptr<logger> // filename_t &tmp_ext = ".tmp", unsigned max_file_size = std::numeric_limits<unsigned>::max(), bool delete_empty_files = true, const
// step_logger_st(const std::string &logger_name, const filename_t &filename, unsigned seconds = 60, const filename_t &tmp_ext = ".tmp", // filename_t &file_header = ""); std::shared_ptr<logger> step_logger_st(const std::string &logger_name, const filename_t &filename,
// unsigned max_file_size = std::numeric_limits<unsigned>::max()); // unsigned seconds = 60, const filename_t &tmp_ext = ".tmp", unsigned max_file_size = std::numeric_limits<unsigned>::max());
// Example for spdlog_impl.h // Example for spdlog_impl.h
// Create a file logger that creates new files with a specified increment // Create a file logger that creates new files with a specified increment
// inline std::shared_ptr<spdlog::logger> spdlog::step_logger_mt( // inline std::shared_ptr<spdlog::logger> spdlog::step_logger_mt(
// const std::string &logger_name, const filename_t &filename_fmt, unsigned seconds, const filename_t &tmp_ext, unsigned max_file_size) // const std::string &logger_name, const filename_t &filename_fmt, unsigned seconds, const filename_t &tmp_ext, unsigned max_file_size,
// bool delete_empty_files, const filename_t &file_header)
// { // {
// return create<spdlog::sinks::step_file_sink_mt>(logger_name, filename_fmt, seconds, tmp_ext, max_file_size); // return create<spdlog::sinks::step_file_sink_mt>(logger_name, filename_fmt, seconds, tmp_ext, max_file_size, delete_empty_files,
// file_header);
// } // }
// inline std::shared_ptr<spdlog::logger> spdlog::step_logger_st( // inline std::shared_ptr<spdlog::logger> spdlog::step_logger_st(
// const std::string &logger_name, const filename_t &filename_fmt, unsigned seconds, const filename_t &tmp_ext, unsigned max_file_size) // const std::string &logger_name, const filename_t &filename_fmt, unsigned seconds, const filename_t &tmp_ext, unsigned max_file_size,
// bool delete_empty_files, const filename_t &file_header)
// { // {
// return create<spdlog::sinks::step_file_sink_st>(logger_name, filename_fmt, seconds, tmp_ext, max_file_size); // return create<spdlog::sinks::step_file_sink_st>(logger_name, filename_fmt, seconds, tmp_ext, max_file_size, delete_empty_files,
// file_header);
// } // }
namespace spdlog { namespace spdlog {
@@ -64,17 +68,27 @@ template<class Mutex, class FileNameCalc = default_step_file_name_calculator>
class step_file_sink SPDLOG_FINAL : public base_sink<Mutex> class step_file_sink SPDLOG_FINAL : public base_sink<Mutex>
{ {
public: public:
step_file_sink(filename_t base_filename, unsigned step_seconds, filename_t tmp_ext, unsigned max_size) step_file_sink(filename_t base_filename, unsigned step_seconds, filename_t tmp_ext, unsigned max_size, bool delete_empty_files,
filename_t file_header)
: _base_filename(std::move(base_filename)) : _base_filename(std::move(base_filename))
, _tmp_ext(std::move(tmp_ext)) , _tmp_ext(std::move(tmp_ext))
, _step_seconds(step_seconds) , _step_seconds(step_seconds)
, _max_size(max_size) , _max_size(max_size)
, _delete_empty_files(delete_empty_files)
{ {
if (step_seconds == 0) if (step_seconds == 0)
{ {
throw spdlog_ex("step_file_sink: Invalid time step in ctor"); throw spdlog_ex("step_file_sink: Invalid time step in ctor");
} }
if (max_size == 0)
if (!file_header.empty())
{
pattern_formatter formatter_for_file_header("%v");
_file_header.raw << file_header;
formatter_for_file_header.format(_file_header);
}
if (max_size <= _file_header.formatted.size())
{ {
throw spdlog_ex("step_file_sink: Invalid max log size in ctor"); throw spdlog_ex("step_file_sink: Invalid max log size in ctor");
} }
@@ -89,6 +103,13 @@ public:
_file_helper.open(_current_filename); _file_helper.open(_current_filename);
_current_size = _file_helper.size(); // expensive. called only once _current_size = _file_helper.size(); // expensive. called only once
if (!_current_size)
{
_current_size += _file_header.formatted.size();
if (_current_size)
_file_helper.write(_file_header);
}
} }
~step_file_sink() ~step_file_sink()
@@ -105,16 +126,34 @@ public:
protected: protected:
void _sink_it(const details::log_msg &msg) override void _sink_it(const details::log_msg &msg) override
{ {
_current_size += msg.formatted.size(); auto msg_size = msg.formatted.size();
if (std::chrono::system_clock::now() >= _tp || _current_size > _max_size)
{ if (std::chrono::system_clock::now() >= _tp || _current_size + msg_size > _max_size)
close_current_file(); {
filename_t new_filename;
std::tie(new_filename, std::ignore) = FileNameCalc::calc_filename(_base_filename, _tmp_ext);
bool change_occured = !details::file_helper::file_exists(new_filename);
if (change_occured)
{
close_current_file();
_current_filename = std::move(new_filename);
_file_helper.open(_current_filename);
}
std::tie(_current_filename, std::ignore) = FileNameCalc::calc_filename(_base_filename, _tmp_ext);
_file_helper.open(_current_filename);
_tp = _next_tp(); _tp = _next_tp();
_current_size = msg.formatted.size();
if (change_occured)
{
_current_size = _file_header.formatted.size();
if (_current_size)
_file_helper.write(_file_header);
}
} }
_current_size += msg_size;
_file_helper.write(msg); _file_helper.write(msg);
} }
@@ -133,13 +172,25 @@ private:
{ {
using details::os::filename_to_str; using details::os::filename_to_str;
filename_t src = _current_filename, target; // Delete empty files, if required
std::tie(target, std::ignore) = details::file_helper::split_by_extenstion(src); if (_delete_empty_files && _current_size <= _file_header.formatted.size())
{
if (details::os::remove(_current_filename) != 0)
{
throw spdlog_ex("step_file_sink: not remove " + filename_to_str(_current_filename), errno);
}
return;
}
filename_t target;
std::tie(target, std::ignore) = details::file_helper::split_by_extenstion(_current_filename);
target += _ext; target += _ext;
if (details::file_helper::file_exists(src) && details::os::rename(src, target) != 0) if (details::file_helper::file_exists(_current_filename) && details::os::rename(_current_filename, target) != 0)
{ {
throw spdlog_ex("step_file_sink: failed renaming " + filename_to_str(src) + " to " + filename_to_str(target), errno); throw spdlog_ex(
"step_file_sink: failed renaming " + filename_to_str(_current_filename) + " to " + filename_to_str(target), errno);
} }
} }
@@ -147,6 +198,7 @@ private:
const filename_t _tmp_ext; const filename_t _tmp_ext;
const std::chrono::seconds _step_seconds; const std::chrono::seconds _step_seconds;
const unsigned _max_size; const unsigned _max_size;
const bool _delete_empty_files;
std::chrono::system_clock::time_point _tp; std::chrono::system_clock::time_point _tp;
filename_t _current_filename; filename_t _current_filename;
@@ -154,6 +206,7 @@ private:
unsigned _current_size; unsigned _current_size;
details::file_helper _file_helper; details::file_helper _file_helper;
details::log_msg _file_header;
}; };
using step_file_sink_mt = step_file_sink<std::mutex>; using step_file_sink_mt = step_file_sink<std::mutex>;

View File

@@ -23,7 +23,6 @@
#include <condition_variable> #include <condition_variable>
#include <exception> #include <exception>
#include <functional> #include <functional>
#include <iostream>
#include <memory> #include <memory>
#include <string> #include <string>
#include <thread> #include <thread>
@@ -83,7 +82,7 @@ class async_log_helper
} }
// copy into log_msg // copy into log_msg
void fill_log_msg(log_msg &msg, std::string* logger_name) void fill_log_msg(log_msg &msg, std::string *logger_name)
{ {
msg.logger_name = logger_name; msg.logger_name = logger_name;
msg.level = level; msg.level = level;
@@ -101,15 +100,11 @@ public:
using clock = std::chrono::steady_clock; using clock = std::chrono::steady_clock;
async_log_helper(std::string logger_name, async_log_helper(std::string logger_name, formatter_ptr formatter, std::vector<sink_ptr> sinks, size_t queue_size,
formatter_ptr formatter, const log_err_handler err_handler, const async_overflow_policy overflow_policy = async_overflow_policy::block_retry,
std::vector<sink_ptr> sinks, std::function<void()> worker_warmup_cb = nullptr,
size_t queue_size, const std::chrono::milliseconds &flush_interval_ms = std::chrono::milliseconds::zero(),
const log_err_handler err_handler, std::function<void()> worker_teardown_cb = nullptr);
const async_overflow_policy overflow_policy = async_overflow_policy::block_retry,
std::function<void()> worker_warmup_cb = nullptr,
const std::chrono::milliseconds &flush_interval_ms = std::chrono::milliseconds::zero(),
std::function<void()> worker_teardown_cb = nullptr);
void log(const details::log_msg &msg); void log(const details::log_msg &msg);
@@ -126,7 +121,7 @@ public:
void set_error_handler(spdlog::log_err_handler err_handler); void set_error_handler(spdlog::log_err_handler err_handler);
private: private:
std::string _logger_name; std::string _logger_name;
formatter_ptr _formatter; formatter_ptr _formatter;
std::vector<std::shared_ptr<sinks::sink>> _sinks; std::vector<std::shared_ptr<sinks::sink>> _sinks;
@@ -176,17 +171,11 @@ private:
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// async_sink class implementation // async_sink class implementation
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
inline spdlog::details::async_log_helper::async_log_helper(std::string logger_name, inline spdlog::details::async_log_helper::async_log_helper(std::string logger_name, formatter_ptr formatter, std::vector<sink_ptr> sinks,
formatter_ptr formatter, size_t queue_size, log_err_handler err_handler, const async_overflow_policy overflow_policy, std::function<void()> worker_warmup_cb,
std::vector<sink_ptr> sinks, const std::chrono::milliseconds &flush_interval_ms, std::function<void()> worker_teardown_cb)
size_t queue_size,
log_err_handler err_handler,
const async_overflow_policy overflow_policy,
std::function<void()> worker_warmup_cb,
const std::chrono::milliseconds &flush_interval_ms,
std::function<void()> worker_teardown_cb)
: _logger_name(std::move(logger_name)) : _logger_name(std::move(logger_name))
, _formatter(std::move(formatter)) , _formatter(std::move(formatter))
, _sinks(std::move(sinks)) , _sinks(std::move(sinks))
, _q(queue_size) , _q(queue_size)
, _err_handler(std::move(err_handler)) , _err_handler(std::move(err_handler))
@@ -251,14 +240,7 @@ inline void spdlog::details::async_log_helper::worker_loop()
{ {
active = process_next_msg(); active = process_next_msg();
} }
catch (const std::exception &ex) SPDLOG_CATCH_AND_HANDLE
{
_err_handler(ex.what());
}
catch (...)
{
_err_handler("Unknown exeption in async logger worker loop.");
}
} }
if (_worker_teardown_cb) if (_worker_teardown_cb)
{ {
@@ -296,7 +278,11 @@ inline bool spdlog::details::async_log_helper::process_next_msg()
{ {
if (s->should_log(incoming_log_msg.level)) if (s->should_log(incoming_log_msg.level))
{ {
s->log(incoming_log_msg); try
{
s->log(incoming_log_msg);
}
SPDLOG_CATCH_AND_HANDLE
} }
} }
handle_flush_interval(); handle_flush_interval();
@@ -334,9 +320,14 @@ inline void spdlog::details::async_log_helper::handle_flush_interval()
// flush all sinks if _flush_interval_ms has expired. only called if queue is empty // flush all sinks if _flush_interval_ms has expired. only called if queue is empty
inline void spdlog::details::async_log_helper::flush_sinks() inline void spdlog::details::async_log_helper::flush_sinks()
{ {
for (auto &s : _sinks) for (auto &s : _sinks)
{ {
s->flush(); try
{
s->flush();
}
SPDLOG_CATCH_AND_HANDLE
} }
_last_flush = os::now(); _last_flush = os::now();
} }

View File

@@ -21,8 +21,8 @@ inline spdlog::async_logger::async_logger(const std::string &logger_name, const
const async_overflow_policy overflow_policy, const std::function<void()> &worker_warmup_cb, 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) const std::chrono::milliseconds &flush_interval_ms, 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( , _async_log_helper(new details::async_log_helper(logger_name, _formatter, _sinks, queue_size, _err_handler, overflow_policy,
logger_name, _formatter, _sinks, queue_size, _err_handler, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb)) worker_warmup_cb, flush_interval_ms, worker_teardown_cb))
{ {
} }

View File

@@ -68,15 +68,7 @@ inline void spdlog::logger::log(level::level_enum lvl, const char *fmt, const Ar
#endif #endif
_sink_it(log_msg); _sink_it(log_msg);
} }
catch (const std::exception &ex) SPDLOG_CATCH_AND_HANDLE
{
_err_handler(ex.what());
}
catch (...)
{
_err_handler("Unknown exception in logger " + _name);
throw;
}
} }
template<typename... Args> template<typename... Args>
@@ -92,15 +84,7 @@ inline void spdlog::logger::log(level::level_enum lvl, const char *msg)
log_msg.raw << msg; log_msg.raw << msg;
_sink_it(log_msg); _sink_it(log_msg);
} }
catch (const std::exception &ex) SPDLOG_CATCH_AND_HANDLE
{
_err_handler(ex.what());
}
catch (...)
{
_err_handler("Unknown exception in logger " + _name);
throw;
}
} }
template<typename T> template<typename T>
@@ -116,15 +100,7 @@ inline void spdlog::logger::log(level::level_enum lvl, const T &msg)
log_msg.raw << msg; log_msg.raw << msg;
_sink_it(log_msg); _sink_it(log_msg);
} }
catch (const std::exception &ex) SPDLOG_CATCH_AND_HANDLE
{
_err_handler(ex.what());
}
catch (...)
{
_err_handler("Unknown exception in logger " + _name);
throw;
}
} }
template<typename Arg1, typename... Args> template<typename Arg1, typename... Args>
@@ -331,10 +307,14 @@ inline void spdlog::logger::_set_formatter(formatter_ptr msg_formatter)
inline void spdlog::logger::flush() inline void spdlog::logger::flush()
{ {
for (auto &sink : _sinks) try
{ {
sink->flush(); for (auto &sink : _sinks)
{
sink->flush();
}
} }
SPDLOG_CATCH_AND_HANDLE
} }
inline void spdlog::logger::_default_err_handler(const std::string &msg) inline void spdlog::logger::_default_err_handler(const std::string &msg)

View File

@@ -237,7 +237,7 @@ inline size_t filesize(FILE *f)
#else // unix #else // unix
int fd = fileno(f); int fd = fileno(f);
// 64 bits(but not in osx or cygwin, where fstat64 is deprecated) // 64 bits(but not in osx or cygwin, where fstat64 is deprecated)
#if !defined(__FreeBSD__) && !defined(__APPLE__) && (defined(__x86_64__) || defined(__ppc64__)) && !defined(__CYGWIN__) #if !defined(__OpenBSD__) && !defined(__FreeBSD__) && !defined(__APPLE__) && !defined(__HAIKU__) && (defined(__x86_64__) || defined(__ppc64__)) && !defined(__CYGWIN__)
struct stat64 st; struct stat64 st;
if (fstat64(fd, &st) == 0) if (fstat64(fd, &st) == 0)
{ {
@@ -282,7 +282,7 @@ inline int utc_minutes_offset(const std::tm &tm = details::os::localtime())
return offset; return offset;
#else #else
#if defined(sun) || defined(__sun) #if defined(sun) || defined(__sun) || defined(_AIX)
// 'tm_gmtoff' field is BSD extension and it's missing on SunOS/Solaris // 'tm_gmtoff' field is BSD extension and it's missing on SunOS/Solaris
struct helper struct helper
{ {
@@ -383,54 +383,6 @@ inline std::string filename_to_str(const filename_t &filename)
} }
#endif #endif
inline std::string errno_to_string(char[256], char *res)
{
return std::string(res);
}
inline std::string errno_to_string(char buf[256], int res)
{
if (res == 0)
{
return std::string(buf);
}
return "Unknown error";
}
// Return errno string (thread safe)
inline std::string errno_str(int err_num)
{
char buf[256];
SPDLOG_CONSTEXPR auto buf_size = sizeof(buf);
#ifdef _WIN32
if (strerror_s(buf, buf_size, err_num) == 0)
{
return std::string(buf);
}
else
{
return "Unknown error";
}
#elif defined(__FreeBSD__) || defined(__APPLE__) || defined(ANDROID) || defined(__SUNPRO_CC) || \
((_POSIX_C_SOURCE >= 200112L) && !defined(_GNU_SOURCE)) // posix version
if (strerror_r(err_num, buf, buf_size) == 0)
{
return std::string(buf);
}
else
{
return "Unknown error";
}
#else // gnu version (might not use the given buf, so its retval pointer must be used)
auto err = strerror_r(err_num, buf, buf_size); // let compiler choose type
return errno_to_string(buf, err); // use overloading to select correct stringify function
#endif
}
inline int pid() inline int pid()
{ {

View File

@@ -62,6 +62,12 @@ public:
std::lock_guard<Mutex> lock(base_sink<Mutex>::_mutex); std::lock_guard<Mutex> lock(base_sink<Mutex>::_mutex);
_sinks.erase(std::remove(_sinks.begin(), _sinks.end(), sink), _sinks.end()); _sinks.erase(std::remove(_sinks.begin(), _sinks.end(), sink), _sinks.end());
} }
void remove_all_sinks()
{
std::lock_guard<Mutex> lock(base_sink<Mutex>::_mutex);
_sinks.clear();
}
}; };
using dist_sink_mt = dist_sink<std::mutex>; using dist_sink_mt = dist_sink<std::mutex>;

View File

@@ -104,7 +104,7 @@ private:
void _print_range(const details::log_msg &msg, size_t start, size_t end) void _print_range(const details::log_msg &msg, size_t start, size_t end)
{ {
DWORD size = static_cast<DWORD>(end - start); DWORD size = static_cast<DWORD>(end - start);
WriteConsoleA(out_handle_, msg.formatted.data() + start, size, nullptr, nullptr); WriteFile(out_handle_, msg.formatted.data() + start, size, nullptr, nullptr);
} }
}; };

View File

@@ -7,14 +7,17 @@
class failing_sink : public spdlog::sinks::sink class failing_sink : public spdlog::sinks::sink
{ {
void log(const spdlog::details::log_msg &msg) override void log(const spdlog::details::log_msg &) override
{ {
throw std::runtime_error("some error happened during log"); throw std::runtime_error("some error happened during log");
} }
void flush() override {} void flush() override
{
throw std::runtime_error("some error happened during flush");
}
}; };
using namespace std;
TEST_CASE("default_error_handler", "[errors]]") TEST_CASE("default_error_handler", "[errors]]")
{ {
prepare_logdir(); prepare_logdir();
@@ -44,7 +47,7 @@ TEST_CASE("custom_error_handler", "[errors]]")
std::string filename = "logs/simple_log.txt"; std::string filename = "logs/simple_log.txt";
auto logger = spdlog::create<spdlog::sinks::simple_file_sink_mt>("logger", filename, true); auto logger = spdlog::create<spdlog::sinks::simple_file_sink_mt>("logger", filename, true);
logger->flush_on(spdlog::level::info); logger->flush_on(spdlog::level::info);
logger->set_error_handler([=](const std::string &msg) { throw custom_ex(); }); logger->set_error_handler([=](const std::string &) { throw custom_ex(); });
logger->info("Good message #1"); logger->info("Good message #1");
#if !defined(SPDLOG_FMT_PRINTF) #if !defined(SPDLOG_FMT_PRINTF)
REQUIRE_THROWS_AS(logger->info("Bad format msg {} {}", "xxx"), custom_ex); REQUIRE_THROWS_AS(logger->info("Bad format msg {} {}", "xxx"), custom_ex);
@@ -57,12 +60,19 @@ TEST_CASE("custom_error_handler", "[errors]]")
TEST_CASE("default_error_handler2", "[errors]]") TEST_CASE("default_error_handler2", "[errors]]")
{ {
auto logger = spdlog::create<failing_sink>("failed_logger"); auto logger = spdlog::create<failing_sink>("failed_logger");
logger->set_error_handler([=](const std::string &msg) { throw custom_ex(); }); logger->set_error_handler([=](const std::string &) { throw custom_ex(); });
REQUIRE_THROWS_AS(logger->info("Some message"), custom_ex); REQUIRE_THROWS_AS(logger->info("Some message"), custom_ex);
} }
TEST_CASE("flush_error_handler", "[errors]]")
{
spdlog::drop_all();
auto logger = spdlog::create<failing_sink>("failed_logger");
logger->set_error_handler([=](const std::string &) { throw custom_ex(); });
REQUIRE_THROWS_AS(logger->flush(), custom_ex);
}
TEST_CASE("async_error_handler", "[errors]]") TEST_CASE("async_error_handler", "[errors]]")
{ {
prepare_logdir(); prepare_logdir();
@@ -71,7 +81,7 @@ TEST_CASE("async_error_handler", "[errors]]")
std::string filename = "logs/simple_async_log.txt"; std::string filename = "logs/simple_async_log.txt";
{ {
auto logger = spdlog::create<spdlog::sinks::simple_file_sink_mt>("logger", filename, true); auto logger = spdlog::create<spdlog::sinks::simple_file_sink_mt>("logger", filename, true);
logger->set_error_handler([=](const std::string &msg) { logger->set_error_handler([=](const std::string &) {
std::ofstream ofs("logs/custom_err.txt"); std::ofstream ofs("logs/custom_err.txt");
if (!ofs) if (!ofs)
throw std::runtime_error("Failed open logs/custom_err.txt"); throw std::runtime_error("Failed open logs/custom_err.txt");
@@ -99,7 +109,7 @@ TEST_CASE("async_error_handler2", "[errors]]")
spdlog::set_async_mode(128); spdlog::set_async_mode(128);
{ {
auto logger = spdlog::create<failing_sink>("failed_logger"); auto logger = spdlog::create<failing_sink>("failed_logger");
logger->set_error_handler([=](const std::string &msg) { logger->set_error_handler([=](const std::string &) {
std::ofstream ofs("logs/custom_err2.txt"); std::ofstream ofs("logs/custom_err2.txt");
if (!ofs) if (!ofs)
throw std::runtime_error("Failed open logs/custom_err2.txt"); throw std::runtime_error("Failed open logs/custom_err2.txt");
@@ -108,6 +118,7 @@ TEST_CASE("async_error_handler2", "[errors]]")
logger->info("Hello failure"); logger->info("Hello failure");
spdlog::drop("failed_logger"); // force logger to drain the queue and shutdown spdlog::drop("failed_logger"); // force logger to drain the queue and shutdown
spdlog::set_sync_mode(); spdlog::set_sync_mode();
logger.reset();
} }
REQUIRE(file_contents("logs/custom_err2.txt") == err_msg); REQUIRE(file_contents("logs/custom_err2.txt") == err_msg);

View File

@@ -50,7 +50,7 @@ TEST_CASE("flush_on", "[flush_on]]")
TEST_CASE("rotating_file_logger1", "[rotating_logger]]") TEST_CASE("rotating_file_logger1", "[rotating_logger]]")
{ {
prepare_logdir(); prepare_logdir();
std::string basename = "logs/rotating_log"; std::string basename = "logs/rotating_log_A";
auto logger = spdlog::rotating_logger_mt("logger", basename, 1024, 0); auto logger = spdlog::rotating_logger_mt("logger", basename, 1024, 0);
for (int i = 0; i < 10; ++i) for (int i = 0; i < 10; ++i)
@@ -70,8 +70,9 @@ TEST_CASE("rotating_file_logger1", "[rotating_logger]]")
TEST_CASE("rotating_file_logger2", "[rotating_logger]]") TEST_CASE("rotating_file_logger2", "[rotating_logger]]")
{ {
prepare_logdir(); prepare_logdir();
std::string basename = "logs/rotating_log"; size_t max_size = 10 * 1024;
auto logger = spdlog::rotating_logger_mt("logger", basename, 1024, 1); std::string basename = "logs/rotating_log.txt";
auto logger = spdlog::rotating_logger_mt("logger", basename, max_size, 1);
for (int i = 0; i < 10; ++i) for (int i = 0; i < 10; ++i)
logger->info("Test message {}", i); logger->info("Test message {}", i);
@@ -88,9 +89,9 @@ TEST_CASE("rotating_file_logger2", "[rotating_logger]]")
} }
logger->flush(); logger->flush();
REQUIRE(get_filesize(filename) <= 1024); REQUIRE(get_filesize(filename) <= max_size);
auto filename1 = basename + ".1"; auto filename1 = "logs/rotating_log.1.txt";
REQUIRE(get_filesize(filename1) <= 1024); REQUIRE(get_filesize(filename1) <= max_size);
} }
TEST_CASE("daily_logger", "[daily_logger]]") TEST_CASE("daily_logger", "[daily_logger]]")

View File

@@ -21,7 +21,7 @@ TEST_CASE("basic async test ", "[async]")
auto test_sink = std::make_shared<spdlog::sinks::test_sink_mt>(); auto test_sink = std::make_shared<spdlog::sinks::test_sink_mt>();
size_t queue_size = 128; size_t queue_size = 128;
size_t messages = 256; size_t messages = 256;
auto logger = spdlog::create_async("as", test_sink, 128, spdlog::async_overflow_policy::block_retry); auto logger = spdlog::create_async("as", test_sink, queue_size, spdlog::async_overflow_policy::block_retry);
for (size_t i = 0; i < messages; i++) for (size_t i = 0; i < messages; i++)
{ {
logger->info("Hello message #{}", i); logger->info("Hello message #{}", i);

View File

@@ -1,10 +1,83 @@
 
Microsoft Visual Studio Solution File, Format Version 12.00 Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2015 # Visual Studio 15
VisualStudioVersion = 14.0 VisualStudioVersion = 15.0.27428.2037
MinimumVisualStudioVersion = 10.0.40219.1 MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "tests", "tests.vcxproj", "{59A07559-5F38-4DD6-A7FA-DB4153690B42}" Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "tests", "tests.vcxproj", "{59A07559-5F38-4DD6-A7FA-DB4153690B42}"
EndProject EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "spdlog", "spdlog", "{7EFD7EC9-512F-4B35-ADFE-49863B2C04A5}"
ProjectSection(SolutionItems) = preProject
..\include\spdlog\async_logger.h = ..\include\spdlog\async_logger.h
..\include\spdlog\common.h = ..\include\spdlog\common.h
..\include\spdlog\formatter.h = ..\include\spdlog\formatter.h
..\include\spdlog\logger.h = ..\include\spdlog\logger.h
..\include\spdlog\spdlog.h = ..\include\spdlog\spdlog.h
..\include\spdlog\tweakme.h = ..\include\spdlog\tweakme.h
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "contrib", "contrib", "{AAD3C108-4E24-4AA8-BA09-4C9A75A881B3}"
ProjectSection(SolutionItems) = preProject
..\include\spdlog\contrib\README.md = ..\include\spdlog\contrib\README.md
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "sinks", "sinks", "{3FB7E4DF-2397-463E-BDAD-32854AB66DFD}"
ProjectSection(SolutionItems) = preProject
..\include\spdlog\contrib\sinks\.gitignore = ..\include\spdlog\contrib\sinks\.gitignore
..\include\spdlog\contrib\sinks\step_file_sink.h = ..\include\spdlog\contrib\sinks\step_file_sink.h
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "details", "details", "{97DED9BF-821E-4A7A-8D13-ED9A739E1F55}"
ProjectSection(SolutionItems) = preProject
..\include\spdlog\details\async_log_helper.h = ..\include\spdlog\details\async_log_helper.h
..\include\spdlog\details\async_logger_impl.h = ..\include\spdlog\details\async_logger_impl.h
..\include\spdlog\details\file_helper.h = ..\include\spdlog\details\file_helper.h
..\include\spdlog\details\log_msg.h = ..\include\spdlog\details\log_msg.h
..\include\spdlog\details\logger_impl.h = ..\include\spdlog\details\logger_impl.h
..\include\spdlog\details\mpmc_blocking_q.h = ..\include\spdlog\details\mpmc_blocking_q.h
..\include\spdlog\details\null_mutex.h = ..\include\spdlog\details\null_mutex.h
..\include\spdlog\details\os.h = ..\include\spdlog\details\os.h
..\include\spdlog\details\pattern_formatter_impl.h = ..\include\spdlog\details\pattern_formatter_impl.h
..\include\spdlog\details\registry.h = ..\include\spdlog\details\registry.h
..\include\spdlog\details\spdlog_impl.h = ..\include\spdlog\details\spdlog_impl.h
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "fmt", "fmt", "{0B649723-CF78-47C0-B1CA-1F173DDBFED4}"
ProjectSection(SolutionItems) = preProject
..\include\spdlog\fmt\fmt.h = ..\include\spdlog\fmt\fmt.h
..\include\spdlog\fmt\ostr.h = ..\include\spdlog\fmt\ostr.h
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "bundled", "bundled", "{1FBA69C4-7EAA-4D60-BCF9-3D59D5A88D32}"
ProjectSection(SolutionItems) = preProject
..\include\spdlog\fmt\bundled\format.cc = ..\include\spdlog\fmt\bundled\format.cc
..\include\spdlog\fmt\bundled\format.h = ..\include\spdlog\fmt\bundled\format.h
..\include\spdlog\fmt\bundled\LICENSE.rst = ..\include\spdlog\fmt\bundled\LICENSE.rst
..\include\spdlog\fmt\bundled\ostream.cc = ..\include\spdlog\fmt\bundled\ostream.cc
..\include\spdlog\fmt\bundled\ostream.h = ..\include\spdlog\fmt\bundled\ostream.h
..\include\spdlog\fmt\bundled\posix.cc = ..\include\spdlog\fmt\bundled\posix.cc
..\include\spdlog\fmt\bundled\posix.h = ..\include\spdlog\fmt\bundled\posix.h
..\include\spdlog\fmt\bundled\printf.cc = ..\include\spdlog\fmt\bundled\printf.cc
..\include\spdlog\fmt\bundled\printf.h = ..\include\spdlog\fmt\bundled\printf.h
..\include\spdlog\fmt\bundled\time.h = ..\include\spdlog\fmt\bundled\time.h
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "sinks", "sinks", "{278CDF3C-6E6D-4FAF-AF79-C1806101B4CB}"
ProjectSection(SolutionItems) = preProject
..\include\spdlog\sinks\android_sink.h = ..\include\spdlog\sinks\android_sink.h
..\include\spdlog\sinks\ansicolor_sink.h = ..\include\spdlog\sinks\ansicolor_sink.h
..\include\spdlog\sinks\base_sink.h = ..\include\spdlog\sinks\base_sink.h
..\include\spdlog\sinks\dist_sink.h = ..\include\spdlog\sinks\dist_sink.h
..\include\spdlog\sinks\file_sinks.h = ..\include\spdlog\sinks\file_sinks.h
..\include\spdlog\sinks\msvc_sink.h = ..\include\spdlog\sinks\msvc_sink.h
..\include\spdlog\sinks\null_sink.h = ..\include\spdlog\sinks\null_sink.h
..\include\spdlog\sinks\ostream_sink.h = ..\include\spdlog\sinks\ostream_sink.h
..\include\spdlog\sinks\sink.h = ..\include\spdlog\sinks\sink.h
..\include\spdlog\sinks\stdout_sinks.h = ..\include\spdlog\sinks\stdout_sinks.h
..\include\spdlog\sinks\syslog_sink.h = ..\include\spdlog\sinks\syslog_sink.h
..\include\spdlog\sinks\wincolor_sink.h = ..\include\spdlog\sinks\wincolor_sink.h
..\include\spdlog\sinks\windebug_sink.h = ..\include\spdlog\sinks\windebug_sink.h
EndProjectSection
EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32 Debug|Win32 = Debug|Win32
@@ -25,4 +98,15 @@ Global
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE
EndGlobalSection EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{AAD3C108-4E24-4AA8-BA09-4C9A75A881B3} = {7EFD7EC9-512F-4B35-ADFE-49863B2C04A5}
{3FB7E4DF-2397-463E-BDAD-32854AB66DFD} = {AAD3C108-4E24-4AA8-BA09-4C9A75A881B3}
{97DED9BF-821E-4A7A-8D13-ED9A739E1F55} = {7EFD7EC9-512F-4B35-ADFE-49863B2C04A5}
{0B649723-CF78-47C0-B1CA-1F173DDBFED4} = {7EFD7EC9-512F-4B35-ADFE-49863B2C04A5}
{1FBA69C4-7EAA-4D60-BCF9-3D59D5A88D32} = {0B649723-CF78-47C0-B1CA-1F173DDBFED4}
{278CDF3C-6E6D-4FAF-AF79-C1806101B4CB} = {7EFD7EC9-512F-4B35-ADFE-49863B2C04A5}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {25A6A4D3-9B25-4071-81B4-99DFDD066255}
EndGlobalSection
EndGlobal EndGlobal

View File

@@ -30,9 +30,6 @@
<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>
<ClCompile Include="test_macros.cpp"> <ClCompile Include="test_macros.cpp">
<Filter>Source Files</Filter> <Filter>Source Files</Filter>
</ClCompile> </ClCompile>
@@ -42,6 +39,9 @@
<ClCompile Include="test_misc.cpp"> <ClCompile Include="test_misc.cpp">
<Filter>Source Files</Filter> <Filter>Source Files</Filter>
</ClCompile> </ClCompile>
<ClCompile Include="errors.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="test_async.cpp"> <ClCompile Include="test_async.cpp">
<Filter>Source Files</Filter> <Filter>Source Files</Filter>
</ClCompile> </ClCompile>