Add a function for formatting log messages

This commit is contained in:
Robbert van der Helm
2020-03-07 16:48:41 +01:00
parent 356d6a6efc
commit 77b2d1b44a
2 changed files with 47 additions and 0 deletions
+28
View File
@@ -1,6 +1,9 @@
#include "logging.h"
#include <chrono>
#include <ctime>
#include <fstream>
#include <iomanip>
#include <iostream>
#ifdef __WINE__
@@ -52,3 +55,28 @@ Logger Logger::create_from_environment(std::string prefix) {
return Logger(std::move(std::cerr), verbosity_level, prefix);
}
}
void Logger::log(const std::string& message) {
const auto current_time = std::chrono::system_clock::now();
const std::time_t timestamp =
std::chrono::system_clock::to_time_t(current_time);
// How did C++ manage to get time formatting libraries without a way to
// actually get a timestamp in a threadsafe way? `localtime_r` in C++ is not
// portable but luckily we only have to support GCC anyway.
std::tm tm;
localtime_r(&timestamp, &tm);
std::ostringstream formatted_message;
formatted_message << "[" << std::put_time(&tm, "%T") << "]";
formatted_message << prefix;
formatted_message << message;
// Flushing a stringstream doesn't do anything, but we need to put a
// linefeed in this string stream rather writing it sprightly to the output
// stream to prevent two messages from being put on the same row
formatted_message << std::endl;
// No flush. Should technically be necessary, but it decreases throughput by
// a lot and it seems to work fine without.
stream << formatted_message.str();
}