ua_log_stdout.c 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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-2018 (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 UA_ENABLE_LOG_COLORS
  14. # define ANSI_COLOR_RED "\x1b[31m"
  15. # define ANSI_COLOR_GREEN "\x1b[32m"
  16. # define ANSI_COLOR_YELLOW "\x1b[33m"
  17. # define ANSI_COLOR_BLUE "\x1b[34m"
  18. # define ANSI_COLOR_MAGENTA "\x1b[35m"
  19. # define ANSI_COLOR_CYAN "\x1b[36m"
  20. # define ANSI_COLOR_RESET "\x1b[0m"
  21. #else
  22. # define ANSI_COLOR_RED ""
  23. # define ANSI_COLOR_GREEN ""
  24. # define ANSI_COLOR_YELLOW ""
  25. # define ANSI_COLOR_BLUE ""
  26. # define ANSI_COLOR_MAGENTA ""
  27. # define ANSI_COLOR_CYAN ""
  28. # define ANSI_COLOR_RESET ""
  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 UA_ENABLE_MULTITHREADING
  38. #include <pthread.h>
  39. static pthread_mutex_t printf_mutex = PTHREAD_MUTEX_INITIALIZER;
  40. #endif
  41. #ifdef __clang__
  42. __attribute__((__format__(__printf__, 4 , 0)))
  43. #endif
  44. void
  45. UA_Log_Stdout_log(void *_, 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. }
  62. void
  63. UA_Log_Stdout_clear(void *logContext) {
  64. }
  65. const UA_Logger UA_Log_Stdout_ = {UA_Log_Stdout_log, NULL, UA_Log_Stdout_clear};
  66. const UA_Logger *UA_Log_Stdout = &UA_Log_Stdout_;