log.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  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 <compat.h>
  23. #include <dpkg-i18n.h>
  24. #include <assert.h>
  25. #include <stdarg.h>
  26. #include <stdio.h>
  27. #include <unistd.h>
  28. #include <time.h>
  29. #include <errno.h>
  30. #include <dpkg.h>
  31. #include <dpkg-db.h>
  32. const char *log_file = NULL;
  33. void
  34. log_message(const char *fmt, ...)
  35. {
  36. static struct varbuf log;
  37. static FILE *logfd = NULL;
  38. char time_str[20];
  39. time_t now;
  40. va_list al;
  41. if (!log_file)
  42. return;
  43. if (!logfd) {
  44. logfd = fopen(log_file, "a");
  45. if (!logfd) {
  46. fprintf(stderr, _("couldn't open log `%s': %s\n"),
  47. log_file, strerror(errno));
  48. log_file = NULL;
  49. return;
  50. }
  51. setlinebuf(logfd);
  52. setcloexec(fileno(logfd), log_file);
  53. }
  54. va_start(al, fmt);
  55. varbufreset(&log);
  56. varbufvprintf(&log, fmt, al);
  57. varbufaddc(&log, 0);
  58. va_end(al);
  59. time(&now);
  60. strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S",
  61. localtime(&now));
  62. fprintf(logfd, "%s %s\n", time_str, log.buf);
  63. }
  64. struct pipef *status_pipes = NULL;
  65. void
  66. statusfd_send(const char *fmt, ...)
  67. {
  68. static struct varbuf vb;
  69. struct pipef *pipef;
  70. const char *p;
  71. int r, l;
  72. va_list al;
  73. if (!status_pipes)
  74. return;
  75. va_start(al, fmt);
  76. varbufreset(&vb);
  77. varbufvprintf(&vb, fmt, al);
  78. varbufaddc(&vb, '\n');
  79. va_end(al);
  80. for (pipef = status_pipes; pipef; pipef = pipef->next) {
  81. for (p = vb.buf, l = vb.used; l; p += r, l -= r) {
  82. r = write(pipef->fd, vb.buf, vb.used);
  83. if (r < 0)
  84. ohshite(_("unable to write to status fd %d"),
  85. pipef->fd);
  86. assert(r && r <= l);
  87. }
  88. }
  89. }