log.h 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*
  2. * log.h
  3. *
  4. * Copyright (C) 2018 Aleksandar Andrejevic <theflash@sdf.lonestar.org>
  5. *
  6. * This program is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU Affero General Public License as
  8. * published by the Free Software Foundation, either version 3 of the
  9. * License, or (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU Affero General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Affero General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. #ifndef _LOG_H_
  20. #define _LOG_H_
  21. #include <common.h>
  22. #include <stdarg.h>
  23. #include <stdio.h>
  24. #define MAX_LOG_MESSAGE_SIZE 256
  25. #ifdef DEBUG
  26. #define TRACE(x) log_write(LOG_DEBUG, x)
  27. #define FTRACE(x, args...) log_write(LOG_DEBUG, x, args)
  28. #else
  29. #define TRACE(x)
  30. #define FTRACE(x, ...)
  31. #endif
  32. typedef enum
  33. {
  34. LOG_DEBUG,
  35. LOG_NORMAL,
  36. LOG_WARNING,
  37. LOG_ERROR,
  38. LOG_CRITICAL,
  39. } log_level_t;
  40. extern char *debug_channel;
  41. extern log_level_t debug_min_level;
  42. void append_log_entry(const char *source, log_level_t level, const char *message);
  43. static inline void log_write(log_level_t level, const char *format, ...)
  44. {
  45. extern const char driver_name[];
  46. static char log_buffer[MAX_LOG_MESSAGE_SIZE] = "";
  47. va_list ap;
  48. va_start(ap, format);
  49. char message[MAX_LOG_MESSAGE_SIZE];
  50. vsnprintf(message, MAX_LOG_MESSAGE_SIZE, format, ap);
  51. va_end(ap);
  52. char *ptr = message;
  53. while (*ptr)
  54. {
  55. char *end = strchr(ptr, '\n');
  56. if (end) *end = '\0';
  57. else break;
  58. char full_message[2 * MAX_LOG_MESSAGE_SIZE];
  59. strcpy(full_message, log_buffer);
  60. strcat(full_message, ptr);
  61. append_log_entry(driver_name, level, full_message);
  62. *log_buffer = '\0';
  63. ptr = end + 1;
  64. }
  65. strcat(log_buffer, ptr);
  66. }
  67. #endif