ua_log_stdout.c 2.4 KB

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