ua_log_stdout.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /* This work is licensed under a Creative Commons CCZero 1.0 Universal License.
  2. * See http://creativecommons.org/publicdomain/zero/1.0/ for more information. */
  3. #include <stdio.h>
  4. #include <stdarg.h>
  5. #include "ua_log_stdout.h"
  6. #include "ua_types_generated.h"
  7. #include "ua_types_generated_handling.h"
  8. /* ANSI escape sequences for color output taken from here:
  9. * https://stackoverflow.com/questions/3219393/stdlib-and-colored-output-in-c*/
  10. #ifdef _WIN32
  11. # define ANSI_COLOR_RED ""
  12. # define ANSI_COLOR_GREEN ""
  13. # define ANSI_COLOR_YELLOW ""
  14. # define ANSI_COLOR_BLUE ""
  15. # define ANSI_COLOR_MAGENTA ""
  16. # define ANSI_COLOR_CYAN ""
  17. # define ANSI_COLOR_RESET ""
  18. #else
  19. # define ANSI_COLOR_RED "\x1b[31m"
  20. # define ANSI_COLOR_GREEN "\x1b[32m"
  21. # define ANSI_COLOR_YELLOW "\x1b[33m"
  22. # define ANSI_COLOR_BLUE "\x1b[34m"
  23. # define ANSI_COLOR_MAGENTA "\x1b[35m"
  24. # define ANSI_COLOR_CYAN "\x1b[36m"
  25. # define ANSI_COLOR_RESET "\x1b[0m"
  26. #endif
  27. #ifdef UA_ENABLE_MULTITHREADING
  28. #include <pthread.h>
  29. static pthread_mutex_t printf_mutex = PTHREAD_MUTEX_INITIALIZER;
  30. #endif
  31. const char *logLevelNames[6] = {"trace", "debug",
  32. ANSI_COLOR_GREEN "info",
  33. ANSI_COLOR_YELLOW "warn",
  34. ANSI_COLOR_RED "error",
  35. ANSI_COLOR_MAGENTA "fatal"};
  36. const char *logCategoryNames[7] = {"network", "channel", "session", "server",
  37. "client", "userland", "securitypolicy"};
  38. #ifdef __clang__
  39. __attribute__((__format__(__printf__, 3 , 0)))
  40. #endif
  41. void
  42. UA_Log_Stdout(UA_LogLevel level, UA_LogCategory category,
  43. const char *msg, va_list args) {
  44. UA_String t = UA_DateTime_toString(UA_DateTime_now());
  45. #ifdef UA_ENABLE_MULTITHREADING
  46. pthread_mutex_lock(&printf_mutex);
  47. #endif
  48. printf("[%.23s] %s/%s" ANSI_COLOR_RESET "\t", t.data, logLevelNames[level], logCategoryNames[category]);
  49. vprintf(msg, args);
  50. printf("\n");
  51. fflush(stdout);
  52. #ifdef UA_ENABLE_MULTITHREADING
  53. pthread_mutex_unlock(&printf_mutex);
  54. #endif
  55. UA_ByteString_deleteMembers(&t);
  56. }