/slog.c

http://github.com/nicolasff/webdis · C · 80 lines · 51 code · 18 blank · 11 comment · 7 complexity · cb0b6954232eb4cf8824f761a379a795 MD5 · raw file

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <stdarg.h>
  4. #include <time.h>
  5. #include <sys/types.h>
  6. #include <unistd.h>
  7. #include <string.h>
  8. #include <sys/stat.h>
  9. #include <fcntl.h>
  10. #include <errno.h>
  11. #include "slog.h"
  12. #include "server.h"
  13. #include "conf.h"
  14. /**
  15. * Initialize log writer.
  16. */
  17. void
  18. slog_init(struct server *s) {
  19. s->log.self = getpid();
  20. if(s->cfg->logfile) {
  21. int old_fd = s->log.fd;
  22. s->log.fd = open(s->cfg->logfile,
  23. O_WRONLY | O_APPEND | O_CREAT, S_IRUSR|S_IWUSR);
  24. /* close old log */
  25. if (old_fd != -1) {
  26. close(old_fd);
  27. }
  28. if (s->log.fd != -1)
  29. return;
  30. fprintf(stderr, "Could not open %s: %s\n", s->cfg->logfile,
  31. strerror(errno));
  32. }
  33. s->log.fd = 2; /* stderr */
  34. }
  35. /**
  36. * Write log message to disk, or stderr.
  37. */
  38. void
  39. slog(struct server *s, log_level level,
  40. const char *body, size_t sz) {
  41. const char *c = ".-*#";
  42. time_t now;
  43. char time_buf[64];
  44. char msg[124];
  45. char line[256]; /* bounds are checked. */
  46. int line_sz, ret;
  47. if(level > s->cfg->verbosity) return; /* too verbose */
  48. if(!s->log.fd) return;
  49. /* limit message size */
  50. sz = sz ? sz:strlen(body);
  51. snprintf(msg, sz + 1 > sizeof(msg) ? sizeof(msg) : sz + 1, "%s", body);
  52. /* get current time */
  53. now = time(NULL);
  54. strftime(time_buf, sizeof(time_buf), "%d %b %H:%M:%S", localtime(&now));
  55. /* generate output line. */
  56. line_sz = snprintf(line, sizeof(line),
  57. "[%d] %s %d %s\n", (int)s->log.self, time_buf, c[level], msg);
  58. /* write to log and flush to disk. */
  59. ret = write(s->log.fd, line, line_sz);
  60. ret = fsync(s->log.fd);
  61. (void)ret;
  62. }