PageRenderTime 38ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/fpm/zlog.c

http://github.com/dreamcat4/php-fpm
C | 113 lines | 81 code | 30 blank | 2 comment | 8 complexity | 118e1c125fd10ec9718ae99d076bd1eb MD5 | raw file
  1. /* $Id: zlog.c,v 1.7 2008/05/22 21:08:32 anight Exp $ */
  2. /* (c) 2004-2007 Andrei Nigmatulin */
  3. #include "fpm_config.h"
  4. #include <stdio.h>
  5. #include <unistd.h>
  6. #include <time.h>
  7. #include <string.h>
  8. #include <stdarg.h>
  9. #include <sys/time.h>
  10. #include <errno.h>
  11. #include "zlog.h"
  12. #define MAX_LINE_LENGTH 1024
  13. static int zlog_fd = -1;
  14. static int zlog_level = ZLOG_NOTICE;
  15. static const char *level_names[] = {
  16. [ZLOG_DEBUG] = "DEBUG",
  17. [ZLOG_NOTICE] = "NOTICE",
  18. [ZLOG_WARNING] = "WARNING",
  19. [ZLOG_ERROR] = "ERROR",
  20. [ZLOG_ALERT] = "ALERT",
  21. };
  22. size_t zlog_print_time(struct timeval *tv, char *timebuf, size_t timebuf_len)
  23. {
  24. struct tm t;
  25. size_t len;
  26. len = strftime(timebuf, timebuf_len, "%b %d %H:%M:%S", localtime_r((const time_t *) &tv->tv_sec, &t));
  27. len += snprintf(timebuf + len, timebuf_len - len, ".%06d", (int) tv->tv_usec);
  28. return len;
  29. }
  30. int zlog_set_fd(int new_fd)
  31. {
  32. int old_fd = zlog_fd;
  33. zlog_fd = new_fd;
  34. return old_fd;
  35. }
  36. int zlog_set_level(int new_value)
  37. {
  38. int old_value = zlog_level;
  39. zlog_level = new_value;
  40. return old_value;
  41. }
  42. void zlog(const char *function, int line, int flags, const char *fmt, ...)
  43. {
  44. struct timeval tv;
  45. char buf[MAX_LINE_LENGTH];
  46. const size_t buf_size = MAX_LINE_LENGTH;
  47. va_list args;
  48. size_t len;
  49. int truncated = 0;
  50. int saved_errno;
  51. if ((flags & ZLOG_LEVEL_MASK) < zlog_level) {
  52. return;
  53. }
  54. saved_errno = errno;
  55. gettimeofday(&tv, 0);
  56. len = zlog_print_time(&tv, buf, buf_size);
  57. len += snprintf(buf + len, buf_size - len, " [%s] %s(), line %d: ", level_names[flags & ZLOG_LEVEL_MASK], function, line);
  58. if (len > buf_size - 1) {
  59. truncated = 1;
  60. }
  61. if (!truncated) {
  62. va_start(args, fmt);
  63. len += vsnprintf(buf + len, buf_size - len, fmt, args);
  64. va_end(args);
  65. if (len >= buf_size) {
  66. truncated = 1;
  67. }
  68. }
  69. if (!truncated) {
  70. if (flags & ZLOG_HAVE_ERRNO) {
  71. len += snprintf(buf + len, buf_size - len, ": %s (%d)", strerror(saved_errno), saved_errno);
  72. if (len >= buf_size) {
  73. truncated = 1;
  74. }
  75. }
  76. }
  77. if (truncated) {
  78. memcpy(buf + buf_size - sizeof("..."), "...", sizeof("...") - 1);
  79. len = buf_size - 1;
  80. }
  81. buf[len++] = '\n';
  82. write(zlog_fd > -1 ? zlog_fd : STDERR_FILENO, buf, len);
  83. }