1
0

hlog.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #include "hlog.h"
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <stdarg.h>
  5. #include <mutex>
  6. #include "htime.h" // for get_datetime
  7. #define LOGBUF_SIZE (1<<13) // 8k
  8. #define LOGFILE_MAXSIZE (1<<23) // 8M
  9. static FILE* s_logfp = NULL;
  10. static char s_logfile[256] = DEFAULT_LOG_FILE;
  11. static int s_loglevel = DEFAULT_LOG_LEVEL;
  12. static char s_logbuf[LOGBUF_SIZE];
  13. static std::mutex s_mutex;
  14. int hlog_set_file(const char* logfile) {
  15. if (logfile && strlen(logfile) > 0) {
  16. strncpy(s_logfile, logfile, 256);
  17. }
  18. if (s_logfp) {
  19. fclose(s_logfp);
  20. s_logfp = NULL;
  21. }
  22. s_logfp = fopen(s_logfile, "a");
  23. return s_logfp ? 0 : -1;
  24. }
  25. void hlog_set_level(int level){
  26. s_loglevel = level;
  27. }
  28. int hlog_printf(int level, const char* fmt, ...) {
  29. if (level < s_loglevel)
  30. return -10;
  31. const char* pcolor = "";
  32. const char* plevel = "";
  33. #define CASE_LOG(id, str, clr) \
  34. case id: plevel = str; pcolor = clr; break;
  35. switch (level) {
  36. FOREACH_LOG(CASE_LOG)
  37. }
  38. #undef CASE_LOG
  39. #ifdef _WIN32
  40. pcolor = "";
  41. #endif
  42. std::lock_guard<std::mutex> locker(s_mutex);
  43. if (!s_logfp){
  44. if (hlog_set_file(s_logfile) != 0)
  45. return -20;
  46. }
  47. if (ftell(s_logfp) > LOGFILE_MAXSIZE){
  48. fclose(s_logfp);
  49. s_logfp = fopen(s_logfile, "w");
  50. if (!s_logfp)
  51. return -30;
  52. }
  53. datetime_t now = get_datetime();
  54. int len = snprintf(s_logbuf, LOGBUF_SIZE, "%s[%04d:%02d:%02d %02d-%02d-%02d.%03d][%s]: ",
  55. pcolor, now.year, now.month, now.day, now.hour, now.min, now.sec, now.ms, plevel);
  56. va_list ap;
  57. va_start(ap, fmt);
  58. len += vsnprintf(s_logbuf + len, LOGBUF_SIZE-len, fmt, ap);
  59. va_end(ap);
  60. fprintf(s_logfp, "%s\n", s_logbuf);
  61. #ifndef _WIN32
  62. fprintf(s_logfp, CL_CLR);
  63. #endif
  64. fflush(NULL);
  65. return len;
  66. }