hlog.cpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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 bool s_logcolor = false;
  13. static char s_logbuf[LOGBUF_SIZE];
  14. static std::mutex s_mutex;
  15. int hlog_set_file(const char* logfile) {
  16. if (logfile && strlen(logfile) > 0) {
  17. strncpy(s_logfile, logfile, 256);
  18. }
  19. if (s_logfp) {
  20. fclose(s_logfp);
  21. s_logfp = NULL;
  22. }
  23. s_logfp = fopen(s_logfile, "a");
  24. return s_logfp ? 0 : -1;
  25. }
  26. void hlog_set_level(int level) {
  27. s_loglevel = level;
  28. }
  29. void hlog_enable_color(bool enable) {
  30. s_logcolor = enable;
  31. }
  32. int hlog_printf(int level, const char* fmt, ...) {
  33. if (level < s_loglevel)
  34. return -10;
  35. const char* pcolor = "";
  36. const char* plevel = "";
  37. #define CASE_LOG(id, str, clr) \
  38. case id: plevel = str; pcolor = clr; break;
  39. switch (level) {
  40. FOREACH_LOG(CASE_LOG)
  41. }
  42. #undef CASE_LOG
  43. if (!s_logcolor)
  44. pcolor = "";
  45. std::lock_guard<std::mutex> locker(s_mutex);
  46. if (!s_logfp) {
  47. if (hlog_set_file(s_logfile) != 0)
  48. return -20;
  49. }
  50. if (ftell(s_logfp) > LOGFILE_MAXSIZE) {
  51. fclose(s_logfp);
  52. s_logfp = fopen(s_logfile, "w");
  53. if (!s_logfp)
  54. return -30;
  55. }
  56. datetime_t now = get_datetime();
  57. int len = snprintf(s_logbuf, LOGBUF_SIZE, "%s[%04d-%02d-%02d %02d:%02d:%02d.%03d][%s]: ",
  58. pcolor, now.year, now.month, now.day, now.hour, now.min, now.sec, now.ms, plevel);
  59. va_list ap;
  60. va_start(ap, fmt);
  61. len += vsnprintf(s_logbuf + len, LOGBUF_SIZE-len, fmt, ap);
  62. va_end(ap);
  63. fprintf(s_logfp, "%s\n", s_logbuf);
  64. if (s_logcolor) {
  65. fprintf(s_logfp, CL_CLR);
  66. }
  67. fflush(NULL);
  68. return len;
  69. }