zc_profile.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /*
  2. * This file is part of the zlog Library.
  3. *
  4. * Copyright (C) 2011 by Hardy Simpson <HardySimpson1984@gmail.com>
  5. *
  6. * Licensed under the LGPL v2.1, see the file COPYING in base directory.
  7. */
  8. #include "fmacros.h"
  9. #include <stdio.h>
  10. #include <string.h>
  11. #include <stdlib.h>
  12. #include <errno.h>
  13. #include <stdarg.h>
  14. #include <time.h>
  15. #include <sys/types.h>
  16. #include <unistd.h>
  17. #include "zc_profile.h"
  18. #include "zc_xplatform.h"
  19. static void zc_time(char *time_str, size_t time_str_size)
  20. {
  21. time_t tt;
  22. struct tm local_time;
  23. time(&tt);
  24. localtime_r(&tt, &local_time);
  25. strftime(time_str, time_str_size, "%m-%d %T", &local_time);
  26. return;
  27. }
  28. int zc_profile_inner(int flag, const char *file, const long line, const char *fmt, ...)
  29. {
  30. va_list args;
  31. char time_str[20 + 1];
  32. FILE *fp = NULL;
  33. static char *debug_log = NULL;
  34. static char *error_log = NULL;
  35. static size_t init_flag = 0;
  36. if (!init_flag) {
  37. init_flag = 1;
  38. debug_log = getenv("ZLOG_PROFILE_DEBUG");
  39. error_log = getenv("ZLOG_PROFILE_ERROR");
  40. }
  41. switch (flag) {
  42. case ZC_DEBUG:
  43. if (debug_log == NULL) return 0;
  44. fp = fopen(debug_log, "a");
  45. if (!fp) return -1;
  46. zc_time(time_str, sizeof(time_str));
  47. fprintf(fp, "%s DEBUG (%d:%s:%ld) ", time_str, getpid(), file, line);
  48. break;
  49. case ZC_WARN:
  50. if (error_log == NULL) return 0;
  51. fp = fopen(error_log, "a");
  52. if (!fp) return -1;
  53. zc_time(time_str, sizeof(time_str));
  54. fprintf(fp, "%s WARN (%d:%s:%ld) ", time_str, getpid(), file, line);
  55. break;
  56. case ZC_ERROR:
  57. if (error_log == NULL) return 0;
  58. fp = fopen(error_log, "a");
  59. if (!fp) return -1;
  60. zc_time(time_str, sizeof(time_str));
  61. fprintf(fp, "%s ERROR (%d:%s:%ld) ", time_str, getpid(), file, line);
  62. break;
  63. }
  64. /* writing file twice(time & msg) is not atomic
  65. * may cause cross
  66. * but avoid log size limit */
  67. va_start(args, fmt);
  68. vfprintf(fp, fmt, args);
  69. va_end(args);
  70. fprintf(fp, "\n");
  71. fclose(fp);
  72. return 0;
  73. }