dbg_log.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /* Copyright (c) 1998-2026 Free Software Foundation, Inc.
  2. This file is part of the GNU C Library.
  3. This program is free software; you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published
  5. by the Free Software Foundation; version 2 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program; if not, see <https://www.gnu.org/licenses/>. */
  13. #include <stdarg.h>
  14. #include <stdio.h>
  15. #include <string.h>
  16. #include <syslog.h>
  17. #include <unistd.h>
  18. #include "dbg_log.h"
  19. #include "nscd.h"
  20. /* if in debug mode and we have a debug file, we write the messages to it,
  21. if in debug mode and no debug file, we write the messages to stderr,
  22. else to syslog. */
  23. static char *logfilename;
  24. FILE *dbgout;
  25. int debug_level;
  26. void
  27. set_logfile (const char *logfile)
  28. {
  29. logfilename = strdup (logfile);
  30. }
  31. int
  32. init_logfile (void)
  33. {
  34. if (logfilename)
  35. {
  36. dbgout = fopen64 (logfilename, "a");
  37. return dbgout == NULL ? 0 : 1;
  38. }
  39. return 1;
  40. }
  41. void
  42. dbg_log (const char *fmt,...)
  43. {
  44. va_list ap;
  45. char msg2[512];
  46. va_start (ap, fmt);
  47. vsnprintf (msg2, sizeof (msg2), fmt, ap);
  48. if (debug_level > 0)
  49. {
  50. time_t t = time (NULL);
  51. struct tm now;
  52. localtime_r (&t, &now);
  53. char buf[256];
  54. strftime (buf, sizeof (buf), "%c", &now);
  55. char msg[1024];
  56. snprintf (msg, sizeof (msg), "%s - %d: %s%s", buf, getpid (), msg2,
  57. msg2[strlen (msg2) - 1] == '\n' ? "" : "\n");
  58. if (dbgout)
  59. {
  60. fputs (msg, dbgout);
  61. fflush (dbgout);
  62. }
  63. else
  64. fputs (msg, stderr);
  65. }
  66. else
  67. syslog (LOG_NOTICE, "%d %s", getpid (), msg2);
  68. va_end (ap);
  69. }