log.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. /*
  2. * dpkg - main program for package management
  3. * log.c - logging related functions
  4. *
  5. * Copyright © 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;
  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. va_start(al, fmt);
  53. varbufreset(&log);
  54. varbufvprintf(&log, fmt, al);
  55. varbufaddc(&log, 0);
  56. va_end(al);
  57. time(&now);
  58. strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S",
  59. localtime(&now));
  60. fprintf(logfd, "%s %s\n", time_str, log.buf);
  61. }
  62. struct pipef *status_pipes = NULL;
  63. void
  64. statusfd_send(const char *fmt, ...)
  65. {
  66. static struct varbuf vb;
  67. struct pipef *pipef;
  68. const char *p;
  69. int r, l;
  70. va_list al;
  71. if (!status_pipes)
  72. return;
  73. va_start(al, fmt);
  74. varbufreset(&vb);
  75. varbufvprintf(&vb, fmt, al);
  76. varbufaddc(&vb, '\n');
  77. va_end(al);
  78. for (pipef = status_pipes; pipef; pipef = pipef->next) {
  79. for (p = vb.buf, l = vb.used; l; p += r, l -= r) {
  80. r = write(pipef->fd, vb.buf, vb.used);
  81. if (r < 0)
  82. ohshite("unable to write to status fd %d",
  83. pipef->fd);
  84. assert(r && r <= l);
  85. }
  86. }
  87. }