ua_log_stdout.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. #define ANSI_COLOR_RED "\x1b[31m"
  11. #define ANSI_COLOR_GREEN "\x1b[32m"
  12. #define ANSI_COLOR_YELLOW "\x1b[33m"
  13. #define ANSI_COLOR_BLUE "\x1b[34m"
  14. #define ANSI_COLOR_MAGENTA "\x1b[35m"
  15. #define ANSI_COLOR_CYAN "\x1b[36m"
  16. #define ANSI_COLOR_RESET "\x1b[0m"
  17. #ifdef UA_ENABLE_MULTITHREADING
  18. #include <pthread.h>
  19. static pthread_mutex_t printf_mutex = PTHREAD_MUTEX_INITIALIZER;
  20. #endif
  21. const char *logLevelNames[6] = {"trace", "debug",
  22. ANSI_COLOR_GREEN "info",
  23. ANSI_COLOR_YELLOW "warn",
  24. ANSI_COLOR_RED "error",
  25. ANSI_COLOR_MAGENTA "fatal"};
  26. const char *logCategoryNames[7] = {"network", "channel", "session", "server",
  27. "client", "userland", "securitypolicy"};
  28. #ifdef __clang__
  29. __attribute__((__format__(__printf__, 3 , 0)))
  30. #endif
  31. void
  32. UA_Log_Stdout(UA_LogLevel level, UA_LogCategory category,
  33. const char *msg, va_list args) {
  34. UA_String t = UA_DateTime_toString(UA_DateTime_now());
  35. #ifdef UA_ENABLE_MULTITHREADING
  36. pthread_mutex_lock(&printf_mutex);
  37. #endif
  38. printf("[%.23s] %s/%s" ANSI_COLOR_RESET "\t", t.data, logLevelNames[level], logCategoryNames[category]);
  39. vprintf(msg, args);
  40. printf("\n");
  41. fflush(stdout);
  42. #ifdef UA_ENABLE_MULTITHREADING
  43. pthread_mutex_unlock(&printf_mutex);
  44. #endif
  45. UA_ByteString_deleteMembers(&t);
  46. }