Skip to content
Repos

DevPlaceApp

C++ 1.9 KB73 lines Opens in site

Directory Raw Download

#include "core/Log.hpp"

#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <filesystem>
#include <mutex>

#include "core/Date.hpp"

namespace dp {

namespace {

constexpr std::uintmax_t kMaxFileBytes = 10u * 1024u * 1024u;
constexpr int kKeepFiles = 3;

std::mutex g_mutex;
std::FILE* g_file = nullptr;
std::string g_path;
Log::Level g_min = Log::Level::Info;

void rotate() {
  if (g_file) std::fclose(g_file);
  g_file = nullptr;
  namespace fs = std::filesystem;
  std::error_code ec;
  for (int i = kKeepFiles - 1; i >= 1; --i) {
    fs::rename(g_path + "." + std::to_string(i), g_path + "." + std::to_string(i + 1), ec);
  }
  fs::rename(g_path, g_path + ".1", ec);
  g_file = std::fopen(g_path.c_str(), "ab");
}

const char* name(Log::Level l) {
  switch (l) {
    case Log::Level::Debug: return "DEBUG";
    case Log::Level::Info: return "INFO";
    case Log::Level::Warn: return "WARN";
    case Log::Level::Error: return "ERROR";
  }
  return "INFO";
}

}  // namespace

void Log::init(const std::string& directory) {
  std::lock_guard<std::mutex> lock(g_mutex);
  if (const char* env = std::getenv("DEVPLACE_LOG_LEVEL")) {
    const std::string v = env;
    if (v == "debug") g_min = Level::Debug;
    else if (v == "warn") g_min = Level::Warn;
    else if (v == "error") g_min = Level::Error;
  }
  std::error_code ec;
  std::filesystem::create_directories(directory, ec);
  g_path = directory + "/devplace.log";
  g_file = std::fopen(g_path.c_str(), "ab");
}

void Log::write(Level level, const std::string& message) {
  std::lock_guard<std::mutex> lock(g_mutex);
  if (level < g_min) return;
  const std::string line = DateCodec::formatIso8601(DateCodec::now()) + " " + name(level) + " " + message + "\n";
  std::fputs(line.c_str(), stderr);
  if (g_file) {
    std::fputs(line.c_str(), g_file);
    std::fflush(g_file);
    if (std::ftell(g_file) > static_cast<long>(kMaxFileBytes)) rotate();
  }
}

}  // namespace dp
21.4ms