log.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. /*
  2. * dpkg - main program for package management
  3. * log.c - logging related functions
  4. *
  5. * Copyright (C) 2005 Scott James Remnant <scott@netsplit.com>
  6. *
  7. * This is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as
  9. * published by the Free Software Foundation; either version 2,
  10. * or (at your option) any later version.
  11. *
  12. * This is distributed in the hope that it will be useful, but
  13. * WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public
  18. * License along with dpkg; if not, write to the Free Software
  19. * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  20. */
  21. #include <config.h>
  22. #include <assert.h>
  23. #include <stdarg.h>
  24. #include <stdio.h>
  25. #include <unistd.h>
  26. #include <time.h>
  27. #include <errno.h>
  28. #include <dpkg.h>
  29. #include <dpkg-db.h>
  30. const char *log_file = NULL;
  31. void
  32. log_message(const char *fmt, ...)
  33. {
  34. static struct varbuf *log = NULL;
  35. static FILE *logfd = NULL;
  36. char time_str[20];
  37. time_t now;
  38. va_list al;
  39. if (!log_file)
  40. return;
  41. if (!logfd) {
  42. logfd = fopen(log_file, "a");
  43. if (!logfd) {
  44. fprintf(stderr, _("couldn't open log `%s': %s\n"),
  45. log_file, strerror(errno));
  46. log_file = NULL;
  47. return;
  48. }
  49. setlinebuf(logfd);
  50. setcloexec(fileno(logfd), log_file);
  51. }
  52. if (!log) {
  53. log = nfmalloc(sizeof(struct varbuf));
  54. varbufinit(log);
  55. } else
  56. varbufreset(log);
  57. va_start(al, fmt);
  58. varbufvprintf(log, fmt, al);
  59. varbufaddc(log, 0);
  60. va_end(al);
  61. time(&now);
  62. strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S",
  63. localtime(&now));
  64. fprintf(logfd, "%s %s\n", time_str, log->buf);
  65. }
  66. struct pipef *status_pipes = NULL;
  67. void
  68. statusfd_send(const char *fmt, ...)
  69. {
  70. static struct varbuf vb;
  71. struct pipef *pipef;
  72. const char *p;
  73. int r, l;
  74. va_list al;
  75. if (!status_pipes)
  76. return;
  77. va_start(al, fmt);
  78. varbufreset(&vb);
  79. varbufvprintf(&vb, fmt, al);
  80. varbufaddc(&vb, '\n');
  81. va_end(al);
  82. for (pipef = status_pipes; pipef; pipef = pipef->next) {
  83. for (p = vb.buf, l = vb.used; l; p += r, l -= r) {
  84. r = write(pipef->fd, vb.buf, vb.used);
  85. if (r < 0)
  86. ohshite("unable to write to status fd %d",
  87. pipef->fd);
  88. assert(r && r <= l);
  89. }
  90. }
  91. }