mirror of
https://github.com/robbert-vdh/yabridge.git
synced 2026-05-07 03:50:11 +02:00
Add a function for formatting log messages
This commit is contained in:
@@ -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(×tamp, &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();
|
||||
}
|
||||
|
||||
@@ -76,11 +76,30 @@ class Logger {
|
||||
*/
|
||||
static Logger create_from_environment(std::string prefix = "");
|
||||
|
||||
/**
|
||||
* Write a message to the log, prefixing it with a timestamp and this
|
||||
* logger's prefix string.
|
||||
*
|
||||
* @param message The message to write.
|
||||
*/
|
||||
void log(const std::string& message);
|
||||
|
||||
// TODO: Add dedicated logging functions for events and the Wine process's
|
||||
// STDOUT and STDERR
|
||||
|
||||
private:
|
||||
/**
|
||||
* The output stream to write the log messages to. Typically either STDERR
|
||||
* or a file stream.
|
||||
*/
|
||||
std::ostream& stream;
|
||||
/**
|
||||
* The verbosity level of this logger instance. Based on this certain
|
||||
* messages may or may not be shown.
|
||||
*/
|
||||
Verbosity verbosity;
|
||||
/**
|
||||
* A prefix that gets prepended before every message.
|
||||
*/
|
||||
std::string prefix;
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user