ua_log_stdout.c 2.6 KB

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