日志系统**

1.设置日志级别

enum LogLevel
  {
    TRACE,
    DEBUG,
    INFO,
    WARN,
    ERROR,
    FATAL,
    NUM_LOG_LEVELS,
  };

2.日志格式

TimeStamp + 级别 + 内容

[2025-05-17 20:32:41][ERROR]This is an error message

3.输出:控制台/文件

4.注意

#include 
#include 
#include 

std::string MyLog::getCurrentTime() {
  auto now = std::chrono::system_clock::now();//获得当前时间
  std::time_t t = std::chrono::system_clock::to_time_t(now)//转换为 C 风格的 time_t
  std::tm *tm = std::localtime(&t);// 转换为本地时间的 tm 结构体

  std::ostringstream oss;
  oss << std::put_time(tm, "%Y-%m-%d %H:%M:%S");

  return oss.str();
}

std::localtime 不是线程安全的,多线程环境下需加锁。 

namespace myLogger {
void MyLog::log(int level, const std::string &message) {
  if (level < level_)
    return;
  std::lock_guard lock(mtx_);

  std::cout << "[" << getCurrentTime() << "]"
            << "[" << LevelToString(level) << "]" << message << std::endl;
}

你可能感兴趣的:(c++,算法,开发语言)