From 8e400a964cc010172e738e7d3c0fb49a99b14311 Mon Sep 17 00:00:00 2001 From: marta-lokhova Date: Tue, 16 Feb 2021 13:41:38 -0800 Subject: [PATCH] Handle failures when setting logging to file --- src/util/Logging.cpp | 33 ++++++++++++++++++++++++++++++--- 1 file changed, 30 insertions(+), 3 deletions(-) diff --git a/src/util/Logging.cpp b/src/util/Logging.cpp index 50ee3bd881..48ef5ee18f 100644 --- a/src/util/Logging.cpp +++ b/src/util/Logging.cpp @@ -134,10 +134,25 @@ Logging::init(bool truncate) // and always pass 'truncate=false' to spdlog, so it always opens in // "ab" == O_APPEND mode. The "portable" way to truncate is to open // an ofstream in out|trunc mode, then immediately close it. + std::ofstream out; if (truncate) { - std::ofstream truncator(filename, std::ios_base::out | - std::ios_base::trunc); + out.open(filename, std::ios_base::out | std::ios_base::trunc); + } + else + { + out.open(filename, std::ios_base::out | std::ios_base::app); + } + + if (out.fail()) + { + throw std::runtime_error(fmt::format( + "Could not open log file {}, check access rights", + filename)); + } + else + { + out.close(); } sinks.emplace_back( @@ -209,7 +224,19 @@ Logging::setLoggingToFile(std::string const& filename) std::lock_guard guard(mLogMutex); mLastFilenamePattern = filename; deinit(); - init(); + try + { + init(); + } + catch (std::runtime_error& e) + { + // Could not initialize logging to file, fallback on + // console-only logging and throw + mLastFilenamePattern.clear(); + deinit(); + init(); + throw; + } #endif }