Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tidy: safer logger #287

Merged
merged 1 commit into from
Jan 13, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 28 additions & 15 deletions manager/MaCh3Logger.h
Original file line number Diff line number Diff line change
Expand Up @@ -63,24 +63,37 @@ void LoggerPrint(const std::string& LibName, LogFunc logFunction, Func&& func, A
// Create a stringstream to capture the output
std::stringstream sss;
// Save the original stream buffers
std::streambuf* coutBuf = std::cout.rdbuf();
std::streambuf* cerrBuf = std::cerr.rdbuf();
std::streambuf* coutBuf = nullptr;
std::streambuf* cerrBuf = nullptr;

// Redirect std::cout and std::cerr to the stringstream buffer
std::cout.rdbuf(sss.rdbuf());
std::cerr.rdbuf(sss.rdbuf());
// This should be rare but in case buffers no longer exist ignore
if (std::cout.rdbuf() && std::cerr.rdbuf()) {
coutBuf = std::cout.rdbuf(); // Save original cout buffer
cerrBuf = std::cerr.rdbuf(); // Save original cerr buffer

// Call the provided function
func(std::forward<Args>(args)...);
// Redirect std::cout and std::cerr to the stringstream buffer
std::cout.rdbuf(sss.rdbuf());
std::cerr.rdbuf(sss.rdbuf());
}

try {
// Call the provided function
func(std::forward<Args>(args)...);

// Restore the original stream buffers
std::cout.rdbuf(coutBuf);
std::cerr.rdbuf(cerrBuf);
// Restore the original stream buffers
if (coutBuf) std::cout.rdbuf(coutBuf);
if (cerrBuf) std::cerr.rdbuf(cerrBuf);

std::string line;
while (std::getline(sss, line))
{
auto formatted_message = fmt::format("[{}] {}", LibName, line);
logFunction(formatted_message);
std::string line;
while (std::getline(sss, line))
{
auto formatted_message = fmt::format("[{}] {}", LibName, line);
logFunction(formatted_message);
}
} catch (...) {
// Restore the original buffers in case of an exception
std::cout.rdbuf(coutBuf);
std::cerr.rdbuf(cerrBuf);
throw;
}
}
Loading