aos_log.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #include "aos_log.h"
  2. #include "apr_portable.h"
  3. aos_log_print_pt aos_log_print = aos_log_print_default;
  4. aos_log_format_pt aos_log_format = aos_log_format_default;
  5. aos_log_level_e aos_log_level = AOS_LOG_WARN;
  6. extern apr_file_t *aos_stderr_file;
  7. void aos_log_set_print(aos_log_print_pt p)
  8. {
  9. aos_log_print = p;
  10. }
  11. void aos_log_set_format(aos_log_format_pt p)
  12. {
  13. aos_log_format = p;
  14. }
  15. void aos_log_set_level(aos_log_level_e level)
  16. {
  17. aos_log_level = level;
  18. }
  19. void aos_log_set_output(apr_file_t *output)
  20. {
  21. aos_stderr_file = output;
  22. }
  23. void aos_log_print_default(const char *message, int len)
  24. {
  25. if (aos_stderr_file == NULL) {
  26. fprintf(stderr, "%s", message);
  27. } else {
  28. apr_size_t bnytes = len;
  29. apr_file_write(aos_stderr_file, message, &bnytes);
  30. }
  31. }
  32. void aos_log_format_default(int level,
  33. const char *file,
  34. int line,
  35. const char *function,
  36. const char *fmt, ...)
  37. {
  38. int len;
  39. apr_time_t t;
  40. int s;
  41. apr_time_exp_t tm;
  42. va_list args;
  43. char buffer[4096];
  44. t = apr_time_now();
  45. if ((s = apr_time_exp_lt(&tm, t)) != APR_SUCCESS) {
  46. return;
  47. }
  48. len = apr_snprintf(buffer, 4090, "[%04d-%02d-%02d %02d:%02d:%02d.%03d] %" APR_INT64_T_FMT " %s:%d ",
  49. tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
  50. tm.tm_hour, tm.tm_min, tm.tm_sec, tm.tm_usec/1000,
  51. (int64_t)apr_os_thread_current(), file, line);
  52. va_start(args, fmt);
  53. len += vsnprintf(buffer + len, 4090 - len, fmt, args);
  54. va_end(args);
  55. while (buffer[len -1] == '\n') len--;
  56. buffer[len++] = '\n';
  57. buffer[len] = '\0';
  58. aos_log_print(buffer, len);
  59. }