wasm_log.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. /*
  2. * Copyright (C) 2019 Intel Corporation. All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "wasm_log.h"
  17. #include "wasm_platform_log.h"
  18. #include "wasm_thread.h"
  19. /**
  20. * The verbose level of the log system. Only those verbose logs whose
  21. * levels are less than or equal to this value are outputed.
  22. */
  23. static int log_verbose_level;
  24. /**
  25. * The lock for protecting the global output stream of logs.
  26. */
  27. static korp_mutex log_stream_lock;
  28. int
  29. _wasm_log_init ()
  30. {
  31. log_verbose_level = 1;
  32. return ws_mutex_init (&log_stream_lock, false);
  33. }
  34. void
  35. _wasm_log_set_verbose_level (int level)
  36. {
  37. log_verbose_level = level;
  38. }
  39. bool
  40. _wasm_log_begin (int level)
  41. {
  42. korp_tid self;
  43. if (level > log_verbose_level) {
  44. return false;
  45. }
  46. /* Try to own the log stream and start the log output. */
  47. ws_mutex_lock (&log_stream_lock);
  48. self = ws_self_thread ();
  49. wasm_printf ("[%X]: ", (int)self);
  50. return true;
  51. }
  52. void
  53. _wasm_log_vprintf (const char *fmt, va_list ap)
  54. {
  55. wasm_vprintf (fmt, ap);
  56. }
  57. void
  58. _wasm_log_printf (const char *fmt, ...)
  59. {
  60. va_list ap;
  61. va_start (ap, fmt);
  62. _wasm_log_vprintf (fmt, ap);
  63. va_end (ap);
  64. }
  65. void
  66. _wasm_log_end ()
  67. {
  68. ws_mutex_unlock (&log_stream_lock);
  69. }
  70. void
  71. _wasm_log (int level, const char *file, int line,
  72. const char *fmt, ...)
  73. {
  74. if (_wasm_log_begin (level)) {
  75. va_list ap;
  76. if (file)
  77. _wasm_log_printf ("%s:%d ", file, line);
  78. va_start (ap, fmt);
  79. _wasm_log_vprintf (fmt, ap);
  80. va_end (ap);
  81. _wasm_log_end ();
  82. }
  83. }