ua_log_stdout.c 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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 "ua_log_stdout.h"
  5. #include "ua_types_generated.h"
  6. #include "ua_types_generated_handling.h"
  7. /* ANSI escape sequences for color output taken from here:
  8. * https://stackoverflow.com/questions/3219393/stdlib-and-colored-output-in-c*/
  9. #ifdef _WIN32
  10. # define ANSI_COLOR_RED ""
  11. # define ANSI_COLOR_GREEN ""
  12. # define ANSI_COLOR_YELLOW ""
  13. # define ANSI_COLOR_BLUE ""
  14. # define ANSI_COLOR_MAGENTA ""
  15. # define ANSI_COLOR_CYAN ""
  16. # define ANSI_COLOR_RESET ""
  17. #else
  18. # define ANSI_COLOR_RED "\x1b[31m"
  19. # define ANSI_COLOR_GREEN "\x1b[32m"
  20. # define ANSI_COLOR_YELLOW "\x1b[33m"
  21. # define ANSI_COLOR_BLUE "\x1b[34m"
  22. # define ANSI_COLOR_MAGENTA "\x1b[35m"
  23. # define ANSI_COLOR_CYAN "\x1b[36m"
  24. # define ANSI_COLOR_RESET "\x1b[0m"
  25. #endif
  26. #ifdef UA_ENABLE_MULTITHREADING
  27. #include <pthread.h>
  28. static pthread_mutex_t printf_mutex = PTHREAD_MUTEX_INITIALIZER;
  29. #endif
  30. const char *logLevelNames[6] = {"trace", "debug",
  31. ANSI_COLOR_GREEN "info",
  32. ANSI_COLOR_YELLOW "warn",
  33. ANSI_COLOR_RED "error",
  34. ANSI_COLOR_MAGENTA "fatal"};
  35. const char *logCategoryNames[7] = {"network", "channel", "session", "server",
  36. "client", "userland", "securitypolicy"};
  37. #ifdef __clang__
  38. __attribute__((__format__(__printf__, 3 , 0)))
  39. #endif
  40. void
  41. UA_Log_Stdout(UA_LogLevel level, UA_LogCategory category,
  42. const char *msg, va_list args) {
  43. UA_Int64 tOffset = UA_DateTime_localTimeUtcOffset();
  44. UA_DateTimeStruct dts = UA_DateTime_toStruct(UA_DateTime_now() + tOffset);
  45. #ifdef UA_ENABLE_MULTITHREADING
  46. pthread_mutex_lock(&printf_mutex);
  47. #endif
  48. printf("[%04u-%02u-%02u %02u:%02u:%02u.%03u (UTC%+05d)] %s/%s" ANSI_COLOR_RESET "\t",
  49. dts.year, dts.month, dts.day, dts.hour, dts.min, dts.sec, dts.milliSec,
  50. (int)(tOffset / UA_DATETIME_SEC / 36), logLevelNames[level], logCategoryNames[category]);
  51. vprintf(msg, args);
  52. printf("\n");
  53. fflush(stdout);
  54. #ifdef UA_ENABLE_MULTITHREADING
  55. pthread_mutex_unlock(&printf_mutex);
  56. #endif
  57. }