Browse Source

vastly simplify logging

rebrand
Martin Dørum 3 years ago
parent
commit
faebbd4c64
3 changed files with 9 additions and 55 deletions
  1. 1
    48
      src/logger.cc
  2. 8
    6
      src/logger.h
  3. 0
    1
      src/main.cc

+ 1
- 48
src/logger.cc View File

@@ -1,54 +1,7 @@
#include "logger.h"

#include <mutex>
#include <vector>
#include <condition_variable>
#include <thread>
#include <iostream>
#include <atomic>

namespace logger {

static std::vector<std::string> queue;
static std::mutex mut;
static std::condition_variable cond;
static std::thread thread;
static std::atomic_bool running;

static void print(const std::string &msg) {
std::cerr << msg << '\n';
}

LogContext::~LogContext() {
running.store(false);
cond.notify_one();
thread.join();
}

void log(std::string msg) {
std::unique_lock<std::mutex> lock(mut);
queue.emplace_back(std::move(msg));
lock.unlock();
cond.notify_one();
}

LogContext init() {
running = true;

thread = std::thread([&] {
std::unique_lock<std::mutex> lock(mut);
while (running.load()) {
cond.wait(lock, [&] { return !queue.empty() || !running.load(); });

for (std::string &msg: queue) {
print(msg);
}

queue.clear();
}
});

return LogContext{};
}
std::mutex mut;

}

+ 8
- 6
src/logger.h View File

@@ -1,15 +1,17 @@
#pragma once

#include <string>
#include <mutex>
#include <iostream>

namespace logger {

struct LogContext {
~LogContext();
};
extern std::mutex mut;

void log(std::string msg);

LogContext init();
template<typename T>
inline void log(const T &msg) {
std::unique_lock<std::mutex> lock(mut);
std::cerr << msg << '\n';
}

}

+ 0
- 1
src/main.cc View File

@@ -186,7 +186,6 @@ int main(int argc, char **argv) {
}
}

logger::LogContext logCtx = logger::init();
parallel::ParallelContext par = parallel::init(jobs);

// Change directory?

Loading…
Cancel
Save