logger.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. /*
  2. * Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
  3. *
  4. * This file is part of ZLToolKit(https://github.com/ZLMediaKit/ZLToolKit).
  5. *
  6. * Use of this source code is governed by MIT license that can be found in the
  7. * LICENSE file in the root of the source tree. All contributing project authors
  8. * may be found in the AUTHORS file in the root of the source tree.
  9. */
  10. #ifndef UTIL_LOGGER_H_
  11. #define UTIL_LOGGER_H_
  12. #include <cstdarg>
  13. #include <set>
  14. #include <map>
  15. #include <fstream>
  16. #include <thread>
  17. #include <memory>
  18. #include <mutex>
  19. #include "util.h"
  20. #include "List.h"
  21. #include "Thread/semaphore.h"
  22. namespace toolkit {
  23. class LogContext;
  24. class LogChannel;
  25. class LogWriter;
  26. class Logger;
  27. using LogContextPtr = std::shared_ptr<LogContext>;
  28. typedef enum {
  29. LTrace = 0, LDebug, LInfo, LWarn, LError
  30. } LogLevel;
  31. Logger &getLogger();
  32. void setLogger(Logger *logger);
  33. /**
  34. * 日志类
  35. */
  36. class Logger : public std::enable_shared_from_this<Logger>, public noncopyable {
  37. public:
  38. friend class AsyncLogWriter;
  39. using Ptr = std::shared_ptr<Logger>;
  40. /**
  41. * 获取日志单例
  42. * @return
  43. */
  44. static Logger &Instance();
  45. explicit Logger(const std::string &loggerName);
  46. ~Logger();
  47. /**
  48. * 添加日志通道,非线程安全的
  49. * @param channel log通道
  50. */
  51. void add(const std::shared_ptr<LogChannel> &channel);
  52. /**
  53. * 删除日志通道,非线程安全的
  54. * @param name log通道名
  55. */
  56. void del(const std::string &name);
  57. /**
  58. * 获取日志通道,非线程安全的
  59. * @param name log通道名
  60. * @return 线程通道
  61. */
  62. std::shared_ptr<LogChannel> get(const std::string &name);
  63. /**
  64. * 设置写log器,非线程安全的
  65. * @param writer 写log器
  66. */
  67. void setWriter(const std::shared_ptr<LogWriter> &writer);
  68. /**
  69. * 设置所有日志通道的log等级
  70. * @param level log等级
  71. */
  72. void setLevel(LogLevel level);
  73. /**
  74. * 获取logger名
  75. * @return logger名
  76. */
  77. const std::string &getName() const;
  78. /**
  79. * 写日志
  80. * @param ctx 日志信息
  81. */
  82. void write(const LogContextPtr &ctx);
  83. private:
  84. /**
  85. * 写日志到各channel,仅供AsyncLogWriter调用
  86. * @param ctx 日志信息
  87. */
  88. void writeChannels(const LogContextPtr &ctx);
  89. void writeChannels_l(const LogContextPtr &ctx);
  90. private:
  91. LogContextPtr _last_log;
  92. std::string _logger_name;
  93. std::shared_ptr<LogWriter> _writer;
  94. std::map<std::string, std::shared_ptr<LogChannel> > _channels;
  95. };
  96. ///////////////////LogContext///////////////////
  97. /**
  98. * 日志上下文
  99. */
  100. class LogContext : public std::ostringstream {
  101. public:
  102. //_file,_function改成string保存,目的是有些情况下,指针可能会失效
  103. //比如说动态库中打印了一条日志,然后动态库卸载了,那么指向静态数据区的指针就会失效
  104. LogContext() = default;
  105. LogContext(LogLevel level, const char *file, const char *function, int line, const char *module_name, const char *flag);
  106. ~LogContext() = default;
  107. LogLevel _level;
  108. int _line;
  109. int _repeat = 0;
  110. std::string _file;
  111. std::string _function;
  112. std::string _thread_name;
  113. std::string _module_name;
  114. std::string _flag;
  115. struct timeval _tv;
  116. const std::string &str();
  117. private:
  118. bool _got_content = false;
  119. std::string _content;
  120. };
  121. /**
  122. * 日志上下文捕获器
  123. */
  124. class LogContextCapture {
  125. public:
  126. using Ptr = std::shared_ptr<LogContextCapture>;
  127. LogContextCapture(Logger &logger, LogLevel level, const char *file, const char *function, int line, const char *flag = "");
  128. LogContextCapture(const LogContextCapture &that);
  129. ~LogContextCapture();
  130. /**
  131. * 输入std::endl(回车符)立即输出日志
  132. * @param f std::endl(回车符)
  133. * @return 自身引用
  134. */
  135. LogContextCapture &operator<<(std::ostream &(*f)(std::ostream &));
  136. template<typename T>
  137. LogContextCapture &operator<<(T &&data) {
  138. if (!_ctx) {
  139. return *this;
  140. }
  141. (*_ctx) << std::forward<T>(data);
  142. return *this;
  143. }
  144. void clear();
  145. private:
  146. LogContextPtr _ctx;
  147. Logger &_logger;
  148. };
  149. ///////////////////LogWriter///////////////////
  150. /**
  151. * 写日志器
  152. */
  153. class LogWriter : public noncopyable {
  154. public:
  155. LogWriter() = default;
  156. virtual ~LogWriter() = default;
  157. virtual void write(const LogContextPtr &ctx, Logger &logger) = 0;
  158. };
  159. class AsyncLogWriter : public LogWriter {
  160. public:
  161. AsyncLogWriter();
  162. ~AsyncLogWriter();
  163. private:
  164. void run();
  165. void flushAll();
  166. void write(const LogContextPtr &ctx, Logger &logger) override;
  167. private:
  168. bool _exit_flag;
  169. semaphore _sem;
  170. std::mutex _mutex;
  171. std::shared_ptr<std::thread> _thread;
  172. List<std::pair<LogContextPtr, Logger *> > _pending;
  173. };
  174. ///////////////////LogChannel///////////////////
  175. /**
  176. * 日志通道
  177. */
  178. class LogChannel : public noncopyable {
  179. public:
  180. LogChannel(const std::string &name, LogLevel level = LTrace);
  181. virtual ~LogChannel();
  182. virtual void write(const Logger &logger, const LogContextPtr &ctx) = 0;
  183. const std::string &name() const;
  184. void setLevel(LogLevel level);
  185. static std::string printTime(const timeval &tv);
  186. protected:
  187. /**
  188. * 打印日志至输出流
  189. * @param ost 输出流
  190. * @param enable_color 是否启用颜色
  191. * @param enable_detail 是否打印细节(函数名、源码文件名、源码行)
  192. */
  193. virtual void format(const Logger &logger, std::ostream &ost, const LogContextPtr &ctx, bool enable_color = true, bool enable_detail = true);
  194. protected:
  195. std::string _name;
  196. LogLevel _level;
  197. };
  198. /**
  199. * 输出日至到广播
  200. */
  201. class EventChannel : public LogChannel {
  202. public:
  203. //输出日志时的广播名
  204. static const std::string kBroadcastLogEvent;
  205. //日志广播参数类型和列表
  206. #define BroadcastLogEventArgs const Logger &logger, const LogContextPtr &ctx
  207. EventChannel(const std::string &name = "EventChannel", LogLevel level = LTrace);
  208. ~EventChannel() override = default;
  209. void write(const Logger &logger, const LogContextPtr &ctx) override;
  210. };
  211. /**
  212. * 输出日志至终端,支持输出日志至android logcat
  213. */
  214. class ConsoleChannel : public LogChannel {
  215. public:
  216. ConsoleChannel(const std::string &name = "ConsoleChannel", LogLevel level = LTrace);
  217. ~ConsoleChannel() override = default;
  218. void write(const Logger &logger, const LogContextPtr &logContext) override;
  219. };
  220. /**
  221. * 输出日志至文件
  222. */
  223. class FileChannelBase : public LogChannel {
  224. public:
  225. FileChannelBase(const std::string &name = "FileChannelBase", const std::string &path = exePath() + ".log", LogLevel level = LTrace);
  226. ~FileChannelBase() override;
  227. void write(const Logger &logger, const LogContextPtr &ctx) override;
  228. bool setPath(const std::string &path);
  229. const std::string &path() const;
  230. protected:
  231. virtual bool open();
  232. virtual void close();
  233. virtual size_t size();
  234. protected:
  235. std::string _path;
  236. std::ofstream _fstream;
  237. };
  238. class Ticker;
  239. /**
  240. * 自动清理的日志文件通道
  241. * 默认最多保存30天的日志
  242. */
  243. class FileChannel : public FileChannelBase {
  244. public:
  245. FileChannel(const std::string &name = "FileChannel", const std::string &dir = exeDir() + "log/", LogLevel level = LTrace);
  246. ~FileChannel() override = default;
  247. /**
  248. * 写日志时才会触发新建日志文件或者删除老的日志文件
  249. * @param logger
  250. * @param stream
  251. */
  252. void write(const Logger &logger, const LogContextPtr &ctx) override;
  253. /**
  254. * 设置日志最大保存天数
  255. * @param max_day 天数
  256. */
  257. void setMaxDay(size_t max_day);
  258. /**
  259. * 设置日志切片文件最大大小
  260. * @param max_size 单位MB
  261. */
  262. void setFileMaxSize(size_t max_size);
  263. /**
  264. * 设置日志切片文件最大个数
  265. * @param max_count 个数
  266. */
  267. void setFileMaxCount(size_t max_count);
  268. private:
  269. /**
  270. * 删除日志切片文件,条件为超过最大保存天数与最大切片个数
  271. */
  272. void clean();
  273. /**
  274. * 检查当前日志切片文件大小,如果超过限制,则创建新的日志切片文件
  275. */
  276. void checkSize(time_t second);
  277. /**
  278. * 创建并切换到下一个日志切片文件
  279. */
  280. void changeFile(time_t second);
  281. private:
  282. bool _can_write = false;
  283. //默认最多保存30天的日志文件
  284. size_t _log_max_day = 30;
  285. //每个日志切片文件最大默认128MB
  286. size_t _log_max_size = 128;
  287. //最多默认保持30个日志切片文件
  288. size_t _log_max_count = 30;
  289. //当前日志切片文件索引
  290. size_t _index = 0;
  291. int64_t _last_day = -1;
  292. time_t _last_check_time = 0;
  293. std::string _dir;
  294. std::set<std::string> _log_file_map;
  295. };
  296. #if defined(__MACH__) || ((defined(__linux) || defined(__linux__)) && !defined(ANDROID))
  297. class SysLogChannel : public LogChannel {
  298. public:
  299. SysLogChannel(const std::string &name = "SysLogChannel", LogLevel level = LTrace);
  300. ~SysLogChannel() override = default;
  301. void write(const Logger &logger, const LogContextPtr &logContext) override;
  302. };
  303. #endif//#if defined(__MACH__) || ((defined(__linux) || defined(__linux__)) && !defined(ANDROID))
  304. class BaseLogFlagInterface {
  305. protected:
  306. virtual ~BaseLogFlagInterface() {}
  307. // 获得日志标记Flag
  308. const char* getLogFlag(){
  309. return _log_flag;
  310. }
  311. void setLogFlag(const char *flag) { _log_flag = flag; }
  312. private:
  313. const char *_log_flag = "";
  314. };
  315. class LoggerWrapper {
  316. public:
  317. template<typename First, typename ...ARGS>
  318. static inline void printLogArray(Logger &logger, LogLevel level, const char *file, const char *function, int line, First &&first, ARGS &&...args) {
  319. LogContextCapture log(logger, level, file, function, line);
  320. log << std::forward<First>(first);
  321. appendLog(log, std::forward<ARGS>(args)...);
  322. }
  323. static inline void printLogArray(Logger &logger, LogLevel level, const char *file, const char *function, int line) {
  324. LogContextCapture log(logger, level, file, function, line);
  325. }
  326. template<typename Log, typename First, typename ...ARGS>
  327. static inline void appendLog(Log &out, First &&first, ARGS &&...args) {
  328. out << std::forward<First>(first);
  329. appendLog(out, std::forward<ARGS>(args)...);
  330. }
  331. template<typename Log>
  332. static inline void appendLog(Log &out) {}
  333. //printf样式的日志打印
  334. static void printLog(Logger &logger, int level, const char *file, const char *function, int line, const char *fmt, ...);
  335. static void printLogV(Logger &logger, int level, const char *file, const char *function, int line, const char *fmt, va_list ap);
  336. };
  337. //可重置默认值
  338. extern Logger *g_defaultLogger;
  339. //用法: DebugL << 1 << "+" << 2 << '=' << 3;
  340. #define WriteL(level) ::toolkit::LogContextCapture(::toolkit::getLogger(), level, __FILE__, __FUNCTION__, __LINE__)
  341. #define TraceL WriteL(::toolkit::LTrace)
  342. #define DebugL WriteL(::toolkit::LDebug)
  343. #define InfoL WriteL(::toolkit::LInfo)
  344. #define WarnL WriteL(::toolkit::LWarn)
  345. #define ErrorL WriteL(::toolkit::LError)
  346. //只能在虚继承BaseLogFlagInterface的类中使用
  347. #define WriteF(level) ::toolkit::LogContextCapture(::toolkit::getLogger(), level, __FILE__, __FUNCTION__, __LINE__, getLogFlag())
  348. #define TraceF WriteF(::toolkit::LTrace)
  349. #define DebugF WriteF(::toolkit::LDebug)
  350. #define InfoF WriteF(::toolkit::LInfo)
  351. #define WarnF WriteF(::toolkit::LWarn)
  352. #define ErrorF WriteF(::toolkit::LError)
  353. //用法: PrintD("%d + %s = %c", 1 "2", 'c');
  354. #define PrintLog(level, ...) ::toolkit::LoggerWrapper::printLog(::toolkit::getLogger(), level, __FILE__, __FUNCTION__, __LINE__, ##__VA_ARGS__)
  355. #define PrintT(...) PrintLog(::toolkit::LTrace, ##__VA_ARGS__)
  356. #define PrintD(...) PrintLog(::toolkit::LDebug, ##__VA_ARGS__)
  357. #define PrintI(...) PrintLog(::toolkit::LInfo, ##__VA_ARGS__)
  358. #define PrintW(...) PrintLog(::toolkit::LWarn, ##__VA_ARGS__)
  359. #define PrintE(...) PrintLog(::toolkit::LError, ##__VA_ARGS__)
  360. //用法: LogD(1, "+", "2", '=', 3);
  361. //用于模板实例化的原因,如果每次打印参数个数和类型不一致,可能会导致二进制代码膨胀
  362. #define LogL(level, ...) ::toolkit::LoggerWrapper::printLogArray(::toolkit::getLogger(), (LogLevel)level, __FILE__, __FUNCTION__, __LINE__, ##__VA_ARGS__)
  363. #define LogT(...) LogL(::toolkit::LTrace, ##__VA_ARGS__)
  364. #define LogD(...) LogL(::toolkit::LDebug, ##__VA_ARGS__)
  365. #define LogI(...) LogL(::toolkit::LInfo, ##__VA_ARGS__)
  366. #define LogW(...) LogL(::toolkit::LWarn, ##__VA_ARGS__)
  367. #define LogE(...) LogL(::toolkit::LError, ##__VA_ARGS__)
  368. } /* namespace toolkit */
  369. #endif /* UTIL_LOGGER_H_ */