log.h 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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 <sdk/defs.h>
  22. #include <string.h>
  23. #include <stdarg.h>
  24. #include <stdio.h>
  25. #define MAX_LOG_MESSAGE_SIZE 256
  26. #ifdef DEBUG
  27. #define TRACE(x, ...) log_write(LOG_DEBUG, x, ##__VA_ARGS__)
  28. #else
  29. #define TRACE(x, ...)
  30. #endif
  31. /* For compatibility: */
  32. #define FTRACE TRACE
  33. typedef enum
  34. {
  35. LOG_DEBUG,
  36. LOG_NORMAL,
  37. LOG_WARNING,
  38. LOG_ERROR,
  39. LOG_CRITICAL,
  40. } log_level_t;
  41. extern char *debug_channel;
  42. extern log_level_t debug_min_level;
  43. void append_log_entry(const char *source, log_level_t level, const char *message);
  44. static inline void log_write(log_level_t level, const char *format, ...)
  45. {
  46. extern const char driver_name[];
  47. static char log_buffer[MAX_LOG_MESSAGE_SIZE] = "";
  48. va_list ap;
  49. va_start(ap, format);
  50. size_t length = vsnprintf(NULL, 0, format, ap);
  51. char message[length + 1];
  52. vsnprintf(message, length + 1, format, ap);
  53. va_end(ap);
  54. char *ptr = message;
  55. while (*ptr)
  56. {
  57. char *end = strchr(ptr, '\n');
  58. if (end) *end = '\0';
  59. else break;
  60. char full_message[strlen(log_buffer) + strlen(ptr) + 1];
  61. strcpy(full_message, log_buffer);
  62. strcat(full_message, ptr);
  63. append_log_entry(driver_name, level, full_message);
  64. *log_buffer = '\0';
  65. ptr = end + 1;
  66. }
  67. strncat(log_buffer, ptr, sizeof(log_buffer) - strlen(log_buffer) - 1);
  68. }
  69. #endif