spdlogwarp.hh 2.32 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/stdout_color_sinks.h>
#include <map>
#include <atomic>

#define LOG_SIZE (1024*1024*10)
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 transto(std::string &x);
  static void cleanup();
private:
  static void monitor_thread();
  static void makesure_dir(const std::string &path);
  static std::string getymd();

  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 std::atomic<int> m_state;
  static bool m_inited;
  static std::mutex m_lock;

};


//template <typename T, typename... Args>
//inline void cslog(const T &x, Args&&...args) throw()
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