log.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /*
  2. * Copyright (C) 2010 Michael Buesch <m@bues.ch>
  3. *
  4. * This program is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU General Public License
  6. * as published by the Free Software Foundation; either version 2
  7. * of the License, or (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. */
  14. #include "log.h"
  15. #include "args.h"
  16. #include <stdlib.h>
  17. #include <stdio.h>
  18. #include <syslog.h>
  19. #include <stdarg.h>
  20. static FILE *log_fd;
  21. static void write_log(FILE *fd, int prio, const char *fmt, va_list args)
  22. {
  23. if (log_fd) {
  24. vfprintf(log_fd, fmt, args);
  25. fflush(log_fd);
  26. } else {
  27. if (cmdargs.background)
  28. vsyslog(prio, fmt, args);
  29. else
  30. vfprintf(fd, fmt, args);
  31. }
  32. }
  33. void log_initialize(void)
  34. {
  35. if (cmdargs.logfile) {
  36. log_fd = fopen(cmdargs.logfile, "w+");
  37. if (!log_fd)
  38. logerr("Failed to open logfile: %s\n", cmdargs.logfile);
  39. }
  40. }
  41. void log_exit(void)
  42. {
  43. if (log_fd)
  44. fclose(log_fd);
  45. log_fd = NULL;
  46. }
  47. void loginfo(const char *fmt, ...)
  48. {
  49. va_list args;
  50. if (loglevel_is_info()) {
  51. va_start(args, fmt);
  52. write_log(stdout, LOG_MAKEPRI(LOG_DAEMON, LOG_INFO), fmt, args);
  53. va_end(args);
  54. }
  55. }
  56. void logerr(const char *fmt, ...)
  57. {
  58. va_list args;
  59. if (loglevel_is_error()) {
  60. va_start(args, fmt);
  61. write_log(stderr, LOG_MAKEPRI(LOG_DAEMON, LOG_ERR), fmt, args);
  62. va_end(args);
  63. }
  64. }
  65. void _logdebug(const char *fmt, ...)
  66. {
  67. va_list args;
  68. if (loglevel_is_debug()) {
  69. va_start(args, fmt);
  70. write_log(stdout, LOG_MAKEPRI(LOG_DAEMON, LOG_DEBUG), fmt, args);
  71. va_end(args);
  72. }
  73. }