about summary refs log tree commit diff stats
path: root/src/logger.cpp
blob: 8a08b583d5bde3fd58185abed65ceefbdad86197 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include "logger.h"

#include <chrono>
#include <fstream>
#include <mutex>
#include <sstream>

#include "global.h"
#include "log_dialog.h"

namespace {

class Logger {
 public:
  Logger() : logfile_(GetAbsolutePath("debug.log")) {}

  void LogLine(const std::string& text) {
    std::lock_guard guard(file_mutex_);
    std::ostringstream line;
    line << "[" << std::chrono::system_clock::now() << "] " << text;

    logfile_ << line.str() << std::endl;
    logfile_.flush();

    if (log_dialog_ != nullptr) {
      log_dialog_->LogMessage(line.str());
    }
  }

  std::string GetContents() {
    std::lock_guard guard(file_mutex_);

    std::ifstream file_in(GetAbsolutePath("debug.log"));
    std::ostringstream buffer;
    buffer << file_in.rdbuf();

    return buffer.str();
  }

  void SetLogDialog(LogDialog* log_dialog) {
    std::lock_guard guard(file_mutex_);
    log_dialog_ = log_dialog;
  }

 private:
  std::ofstream logfile_;
  std::mutex file_mutex_;
  LogDialog* log_dialog_ = nullptr;
};

Logger& GetLogger() {
  static Logger* instance = new Logger();
  return *instance;
}

}  // namespace

void TrackerLog(std::string text) { GetLogger().LogLine(text); }

std::string TrackerReadPastLog() { return GetLogger().GetContents(); }

void TrackerSetLogDialog(LogDialog* log_dialog) {
  GetLogger().SetLogDialog(log_dialog);
}