logging.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. /*
  2. * Copyright 2011-2013 Con Kolivas
  3. * Copyright 2012-2014 Luke Dashjr
  4. * Copyright 2013 Andrew Smith
  5. *
  6. * This program is free software; you can redistribute it and/or modify it
  7. * under the terms of the GNU General Public License as published by the Free
  8. * Software Foundation; either version 3 of the License, or (at your option)
  9. * any later version. See COPYING for more details.
  10. */
  11. #include "config.h"
  12. #include <stdbool.h>
  13. #include <unistd.h>
  14. #include "compat.h"
  15. #include "logging.h"
  16. #include "miner.h"
  17. bool opt_debug = false;
  18. bool opt_debug_console = false; // Only used if opt_debug is also enabled
  19. bool opt_log_output = false;
  20. bool opt_log_microseconds;
  21. /* per default priorities higher than LOG_NOTICE are logged */
  22. int opt_log_level = LOG_NOTICE;
  23. static void _my_log_curses(int prio, const char *datetime, const char *str)
  24. {
  25. #ifdef HAVE_CURSES
  26. extern bool use_curses;
  27. if (use_curses && _log_curses_only(prio, datetime, str))
  28. ;
  29. else
  30. #endif
  31. {
  32. last_logstatusline_len = -1;
  33. printf("\n %s %s\r", datetime, str);
  34. fflush(stdout);
  35. }
  36. }
  37. /* high-level logging function, based on global opt_log_level */
  38. /*
  39. * log function
  40. */
  41. void _applog(int prio, const char *str)
  42. {
  43. #ifdef HAVE_SYSLOG_H
  44. if (use_syslog) {
  45. syslog(prio, "%s", str);
  46. }
  47. #else
  48. if (0) {}
  49. #endif
  50. else {
  51. bool writetocon =
  52. (opt_debug_console || (opt_log_output && prio != LOG_DEBUG) || prio <= LOG_NOTICE)
  53. && !(opt_quiet && prio != LOG_ERR);
  54. bool writetofile = !isatty(fileno((FILE *)stderr));
  55. if (!(writetocon || writetofile))
  56. return;
  57. char datetime[64];
  58. if (opt_log_microseconds)
  59. {
  60. struct timeval tv;
  61. struct tm tm;
  62. bfg_gettimeofday(&tv);
  63. localtime_r(&tv.tv_sec, &tm);
  64. snprintf(datetime, sizeof(datetime), "[%d-%02d-%02d %02d:%02d:%02d.%06ld]",
  65. tm.tm_year + 1900,
  66. tm.tm_mon + 1,
  67. tm.tm_mday,
  68. tm.tm_hour,
  69. tm.tm_min,
  70. tm.tm_sec,
  71. (long)tv.tv_usec);
  72. }
  73. else
  74. get_now_datestamp(datetime, sizeof(datetime));
  75. if (writetofile || writetocon)
  76. {
  77. bfg_console_lock();
  78. /* Only output to stderr if it's not going to the screen as well */
  79. if (writetofile) {
  80. fprintf(stderr, " %s %s\n", datetime, str); /* atomic write to stderr */
  81. fflush(stderr);
  82. }
  83. if (writetocon)
  84. _my_log_curses(prio, datetime, str);
  85. bfg_console_unlock();
  86. }
  87. }
  88. }