spdlogwarp.hh 2.87 KB
/*
 *
 *  Created on: 2020-12-13
 *      Author: liuhang
 */
#ifndef _SLOG_WARPPER_HH_
#define _SLOG_WARPPER_HH_
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <spdlog/spdlog.h>
#include <spdlog/logger.h>
#include <spdlog/fmt/fmt.h>
#include <spdlog/sinks/rotating_file_sink.h>
#include <spdlog/sinks/daily_file_sink.h>
#include <spdlog/sinks/stdout_color_sinks.h>
#include <map>
#include <atomic>

/*********************配置类宏,根据自己需求修改**********************************/
#define IS_ROTATING_MODE

#if defined(IS_ROTATING_MODE) // 循环模式,每个logger对应的文件大小LOG_SIZE MB,最多50个文件,循环利用,不需要清理
#define LOG_SIZE (1024*1024*10)
#define MAX_FILES 50
#else // daily模式,每天每个logger生成一个新的文件。需要有清理逻辑
#define DAILY_HOUR 1
#define DAILY_MINUTE 0
#endif

/*****************************************************************************/

class SLog {
public:
  static void init(const std::string& logdir, const std::string& appname) ;
  static std::shared_ptr<spdlog::logger> global(){
    while (m_state)
      std::this_thread::sleep_for(std::chrono::milliseconds(1));
    return m_globalLog;
  }
  static inline bool has_inited(){return m_inited;};

  static std::shared_ptr<spdlog::logger> get(const std::string &name);
  static std::shared_ptr<spdlog::logger> get_trace(const std::string &name);

  template <typename... Args>
  static void write(const std::string &name, std::string text, Args &&... args)
  {
    transto(text);
    get(name)->info(text, std::forward<Args>(args)...);
  }

  template <typename... Args>
  static void trace(const std::string &name, const std::string &text, Args&&...args)
  {
    get_trace(name)->trace(text, std::forward<Args>(args)...);
  }

  static void dump_trace();
  static void change_level(spdlog::level::level_enum log_level);
  static void cleanup();
  static void transto(std::string &x);
private:
  static void monitor_thread();
  static void makesure_dir(const std::string &path);
  static std::string getymd();
private:
  static std::shared_ptr<spdlog::logger> m_globalLog;
  static std::map<std::string, std::shared_ptr<spdlog::logger>> m_trace;
  static std::map<std::string, std::shared_ptr<spdlog::logger>> m_loggers;
  static std::string m_logdir;
  static std::string m_appname;
  static std::string m_lastymd;
  static spdlog::level::level_enum m_sinkslevel;
  static spdlog::level::level_enum m_level;
  static std::atomic<int> m_state;
  static bool m_inited;
  static std::mutex m_lock;

};

template <typename... Args>
inline void cslog(std::string x, Args&&...args) throw()
{
  for (std::size_t i = 0; i < x.length() - 1; i++)
  {
    if (x[i] == '%' && x[i + 1] != '%' && x[std::max((int)i - 1, 0)] != '\\')
    {
      x[i] = '{';
      x[i+1] = '}';
    }
  }

  SLog::global()->info(x, std::forward<Args>(args)...);
}
void cslog(const char *text) ;

#endif