summaryrefslogtreecommitdiff
path: root/src/logger_file.cc
blob: ad11398a382760f4e98e57579141a9e37438b3cd (plain)
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
#include "common.hh"

#include "logger_base.hh"

#include <fstream>
#include <mutex>

namespace {

class LoggerFile : public LoggerBase {
public:
  explicit LoggerFile(std::filesystem::path const& path)
    : out_(path, std::ios::out | std::ios::app) {}

  bool good() const {
    return out_.good();
  }

protected:
  void msg(Level lvl, std::string_view msg) override {
    std::lock_guard<std::mutex> lock(mutex_);
    switch (lvl) {
    case Level::ERR:
      out_ << "Error: " << msg << std::endl;
      break;
    case Level::WARN:
      out_ << "Warning: " << msg << std::endl;
      break;
    case Level::INFO:
      out_ << msg << std::endl;
      break;
    case Level::DBG:
      out_ << "Debug: " << msg << std::endl;
      break;
    }
  }

private:
  std::mutex mutex_;
  std::fstream out_;
};

}  // namespace

std::unique_ptr<Logger> Logger::create_file(std::filesystem::path const& path,
                                            Logger* fallback) {
  auto logger = std::make_unique<LoggerFile>(path);
  if (logger->good())
    return logger;
  fallback->warn("Unable to open %s for appending.", path.c_str());
  return nullptr;
}