Log4CPP.h 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. #ifndef LOG4CPP_H
  2. #define LOG4CPP_H
  3. #include <log4cpp/Category.hh>
  4. #include <log4cpp/Appender.hh>
  5. #include <log4cpp/FileAppender.hh>
  6. #include <log4cpp/RollingFileAppender.hh>
  7. #include <log4cpp/OstreamAppender.hh>
  8. #include <log4cpp/Layout.hh>
  9. #include <log4cpp/PatternLayout.hh>
  10. #include <log4cpp/Priority.hh>
  11. #include <string>
  12. #include <memory>
  13. #include <unordered_map>
  14. #include <mutex>
  15. #include <sstream>
  16. #include <type_traits>
  17. #include <cstring>
  18. #include <vector>
  19. #include <map>
  20. #include <chrono>
  21. #include <iomanip>
  22. // 前置声明
  23. class LogInstance;
  24. // 日志实例管理器(全局唯一,管理所有模块的日志实例)
  25. class LogManager {
  26. public:
  27. static LogManager& getInstance() {
  28. static LogManager instance;
  29. return instance;
  30. }
  31. // 注册模块日志实例
  32. void registerInstance(const std::string& module, LogInstance* instance) {
  33. std::lock_guard<std::mutex> lock(mtx_);
  34. instances_[module] = instance;
  35. }
  36. // 获取模块日志实例
  37. LogInstance* getInstance(const std::string& module) {
  38. std::lock_guard<std::mutex> lock(mtx_);
  39. auto it = instances_.find(module);
  40. return (it != instances_.end()) ? it->second : nullptr;
  41. }
  42. // 移除模块日志实例
  43. void unregisterInstance(const std::string& module) {
  44. std::lock_guard<std::mutex> lock(mtx_);
  45. instances_.erase(module);
  46. }
  47. // 获取所有注册的模块名
  48. std::vector<std::string> getRegisteredModules() {
  49. std::lock_guard<std::mutex> lock(mtx_);
  50. std::vector<std::string> modules;
  51. for (const auto& pair : instances_) {
  52. modules.push_back(pair.first);
  53. }
  54. return modules;
  55. }
  56. private:
  57. LogManager() = default;
  58. ~LogManager() = default;
  59. LogManager(const LogManager&) = delete;
  60. LogManager& operator=(const LogManager&) = delete;
  61. std::unordered_map<std::string, LogInstance*> instances_;
  62. std::mutex mtx_;
  63. };
  64. // 日志配置结构体
  65. struct LogConfig {
  66. std::string root_level = "DEBUG";
  67. std::string log_dir = "logs";
  68. std::string history_dir = "logs/history";
  69. unsigned int max_file_size = 10; // MB
  70. int max_backups = 5;
  71. std::string file_pattern = "%d{%Y-%m-%d %H:%M:%S.%l} [%p] - %F::%M@%L %m%n";
  72. std::string console_pattern = "%d{%H:%M:%S.%l} [%p] - %F::%M@%L %m%n";
  73. std::string log_file_name; // 自定义日志文件名(为空则使用模块名)
  74. };
  75. // 日志实例类(每个动态库一个实例)
  76. class LogInstance {
  77. public:
  78. LogInstance() = default;
  79. ~LogInstance() { destroyLog(); }
  80. // 初始化日志(module:模块名,确保唯一;configFile:可为空使用默认配置)
  81. bool init(const std::string& logHostName,
  82. const std::string& module,
  83. const std::string& configFile = "",
  84. bool toScreen = false);
  85. // 销毁日志
  86. void destroyLog();
  87. // 设置日志级别
  88. void setPriority(log4cpp::Priority::PriorityLevel consoleLevel,
  89. log4cpp::Priority::PriorityLevel fileLevel);
  90. // 日志输出接口(内部使用)
  91. template <typename... Args>
  92. void log(log4cpp::Priority::PriorityLevel level, const char* file, int line, const char* function,
  93. const std::string& format, Args&&... args) {
  94. if (!isInitialized_) return;
  95. std::lock_guard<std::mutex> lock(logMtx_);
  96. // 格式化消息
  97. std::string formattedMsg = formatMessage(format, std::forward<Args>(args)...);
  98. // 添加代码位置信息
  99. std::string location;
  100. if (file && function) {
  101. // 提取文件名(不含路径)
  102. const char* filename = strrchr(file, '/');
  103. if (!filename) filename = strrchr(file, '\\');
  104. filename = filename ? filename + 1 : file;
  105. std::ostringstream oss;
  106. oss << filename << "::" << function << "@" << line;
  107. location = oss.str();
  108. }
  109. // 输出到文件
  110. if (logCat) {
  111. if (!location.empty()) {
  112. logCat->log(level, "%s - %s", location.c_str(), formattedMsg.c_str());
  113. }
  114. else {
  115. logCat->log(level, "%s", formattedMsg.c_str());
  116. }
  117. }
  118. // 输出到控制台
  119. if (outToScreen && coutCat) {
  120. if (!location.empty()) {
  121. coutCat->log(level, "%s - %s", location.c_str(), formattedMsg.c_str());
  122. }
  123. else {
  124. coutCat->log(level, "%s", formattedMsg.c_str());
  125. }
  126. }
  127. }
  128. bool isInitialized() const { return isInitialized_; }
  129. const std::string& getModule() const { return moduleName; }
  130. const LogConfig& getConfig() const { return config_; }
  131. const std::string& getLogFileName() const { return actualLogFileName; }
  132. private:
  133. // 解析配置文件
  134. bool parseConfigFile(const std::string& configFile, LogConfig& config);
  135. // 创建目录
  136. bool createDirectory(const std::string& dir);
  137. // 获取当前时间(带毫秒)
  138. void getCurrentTimeWithMs(std::string& timeStr);
  139. // 转换日志级别
  140. log4cpp::Priority::PriorityLevel parseLogLevel(const std::string& levelStr);
  141. // 移动旧日志到历史目录
  142. void moveOldLogsToHistory();
  143. // 格式化消息(替换 {$} 占位符)
  144. template <typename... Args>
  145. std::string formatMessage(const std::string& format, Args&&... args) {
  146. std::string result = format;
  147. std::vector<std::string> replacements;
  148. // 收集所有参数
  149. (replacements.push_back(toString(std::forward<Args>(args))), ...);
  150. // 替换所有 {$} 占位符
  151. size_t pos = 0;
  152. int argIndex = 0;
  153. while ((pos = result.find("{$}", pos)) != std::string::npos) {
  154. if (argIndex < replacements.size()) {
  155. result.replace(pos, 3, replacements[argIndex]);
  156. pos += replacements[argIndex].length();
  157. argIndex++;
  158. }
  159. else {
  160. // 参数不足,保留占位符
  161. pos += 3;
  162. }
  163. }
  164. return result;
  165. }
  166. // 类型转换为字符串
  167. template <typename T>
  168. std::string toString(T&& value);
  169. LogConfig config_;
  170. std::string logHost;
  171. std::string moduleName;
  172. std::string actualLogFileName; // 实际使用的日志文件名
  173. bool outToScreen = false;
  174. bool isInitialized_ = false;
  175. // log4cpp组件
  176. log4cpp::Category* logCat = nullptr;
  177. log4cpp::Category* coutCat = nullptr;
  178. log4cpp::RollingFileAppender* rollLogFile = nullptr;
  179. log4cpp::OstreamAppender* logScreen = nullptr;
  180. log4cpp::PatternLayout* logLayout = nullptr;
  181. log4cpp::PatternLayout* screenLayout = nullptr;
  182. // 线程安全锁
  183. std::mutex logMtx_;
  184. };
  185. // 日志模块初始化函数
  186. bool initLogModule(const std::string& logHost,
  187. const std::string& module,
  188. const std::string& configFile = "",
  189. bool toScreen = false);
  190. // 日志模块销毁函数
  191. void destroyLogModule(const std::string& module);
  192. // 获取所有已初始化的日志模块
  193. std::vector<std::string> getInitializedLogModules();
  194. // 销毁所有日志模块
  195. void destroyAllLogModules();
  196. // 类型转换实现
  197. template <typename T>
  198. std::string LogInstance::toString(T&& value) {
  199. using DecayedT = std::decay_t<T>;
  200. try {
  201. if constexpr (std::is_same_v<DecayedT, std::string> ||
  202. std::is_same_v<DecayedT, char*> ||
  203. std::is_same_v<DecayedT, const char*>) {
  204. return std::forward<T>(value);
  205. }
  206. else if constexpr (std::is_arithmetic_v<DecayedT> || std::is_enum_v<DecayedT>) {
  207. std::ostringstream oss;
  208. oss << value;
  209. return oss.str();
  210. }
  211. else {
  212. std::ostringstream oss;
  213. oss << std::forward<T>(value);
  214. return oss.str();
  215. }
  216. }
  217. catch (...) {
  218. return "[LOG_CONVERT_ERROR]";
  219. }
  220. }
  221. #endif // LOG4CPP_H