1
0
mirror of https://github.com/gabime/spdlog.git synced 2025-01-27 09:56:31 +00:00

Compare commits

...

2 Commits

Author SHA1 Message Date
Gabi Melman
5efccfa5e2 Fix #1828 2021-02-13 16:11:07 +02:00
Gabi Melman
89e737a258 Handle invalid handle in wincolor sink 2021-02-13 15:00:35 +02:00
2 changed files with 19 additions and 9 deletions

View File

@ -32,8 +32,13 @@ SPDLOG_INLINE stdout_sink_base<ConsoleMutex>::stdout_sink_base(FILE *file)
{
#ifdef _WIN32
// get windows handle from the FILE* object
handle_ = (HANDLE)::_get_osfhandle(::_fileno(file_));
if (handle_ == INVALID_HANDLE_VALUE)
handle_ = (HANDLE)::_get_osfhandle(::_fileno(file_));
// don't throw to support cases where no console is attached,
// and let the log method to do nothing if (handle_ == INVALID_HANDLE_VALUE).
// throw only if non stdout/stderr target is requested (probably regular file and not console).
if (handle_ == INVALID_HANDLE_VALUE && file != stdout && file != stderr)
{
throw_spdlog_ex("spdlog::stdout_sink_base: _get_osfhandle() failed", errno);
}
@ -43,6 +48,11 @@ SPDLOG_INLINE stdout_sink_base<ConsoleMutex>::stdout_sink_base(FILE *file)
template<typename ConsoleMutex>
SPDLOG_INLINE void stdout_sink_base<ConsoleMutex>::log(const details::log_msg &msg)
{
if (handle_ == INVALID_HANDLE_VALUE)
{
return;
}
std::lock_guard<mutex_t> lock(mutex_);
memory_buf_t formatted;
formatter_->format(msg, formatted);

View File

@ -29,9 +29,8 @@ SPDLOG_INLINE wincolor_sink<ConsoleMutex>::wincolor_sink(void *out_handle, color
{
// check if out_handle is points to the actual console.
// ::GetConsoleMode() should return 0 if it is redirected or not valid console handle.
DWORD console_mode;
DWORD console_mode;
in_console_ = ::GetConsoleMode(static_cast<HANDLE>(out_handle_), &console_mode) != 0;
set_color_mode(mode);
colors_[level::trace] = WHITE;
colors_[level::debug] = CYAN;
@ -59,6 +58,11 @@ void SPDLOG_INLINE wincolor_sink<ConsoleMutex>::set_color(level::level_enum leve
template<typename ConsoleMutex>
void SPDLOG_INLINE wincolor_sink<ConsoleMutex>::log(const details::log_msg &msg)
{
if (out_handle_ == INVALID_HANDLE_VALUE)
{
return;
}
std::lock_guard<mutex_t> lock(mutex_);
msg.color_range_start = 0;
msg.color_range_end = 0;
@ -148,11 +152,7 @@ void SPDLOG_INLINE wincolor_sink<ConsoleMutex>::print_range_(const memory_buf_t
template<typename ConsoleMutex>
void SPDLOG_INLINE wincolor_sink<ConsoleMutex>::write_to_file_(const memory_buf_t &formatted)
{
if (out_handle_ == nullptr) // no console and no file redirect
{
return;
}
{
auto size = static_cast<DWORD>(formatted.size());
DWORD bytes_written = 0;
bool ok = ::WriteFile(static_cast<HANDLE>(out_handle_), formatted.data(), size, &bytes_written, nullptr) != 0;