MMKVLog_Android.cpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*
  2. * Tencent is pleased to support the open source community by making
  3. * MMKV available.
  4. *
  5. * Copyright (C) 2019 THL A29 Limited, a Tencent company.
  6. * All rights reserved.
  7. *
  8. * Licensed under the BSD 3-Clause License (the "License"); you may not use
  9. * this file except in compliance with the License. You may obtain a copy of
  10. * the License at
  11. *
  12. * https://opensource.org/licenses/BSD-3-Clause
  13. *
  14. * Unless required by applicable law or agreed to in writing, software
  15. * distributed under the License is distributed on an "AS IS" BASIS,
  16. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17. * See the License for the specific language governing permissions and
  18. * limitations under the License.
  19. */
  20. #include "MMKVLog.h"
  21. #ifdef ENABLE_MMKV_LOG
  22. # ifdef MMKV_ANDROID
  23. # include <android/log.h>
  24. # include <cstdarg>
  25. # include <string>
  26. using namespace std;
  27. constexpr auto APP_NAME = "MMKV";
  28. static android_LogPriority MMKVLogLevelDesc(MMKVLogLevel level) {
  29. switch (level) {
  30. case MMKVLogDebug:
  31. return ANDROID_LOG_DEBUG;
  32. case MMKVLogInfo:
  33. return ANDROID_LOG_INFO;
  34. case MMKVLogWarning:
  35. return ANDROID_LOG_WARN;
  36. case MMKVLogError:
  37. return ANDROID_LOG_ERROR;
  38. default:
  39. return ANDROID_LOG_UNKNOWN;
  40. }
  41. }
  42. void _MMKVLogWithLevel(MMKVLogLevel level, const char *filename, const char *func, int line, const char *format, ...) {
  43. if (level >= g_currentLogLevel) {
  44. string message;
  45. char buffer[16];
  46. va_list args;
  47. va_start(args, format);
  48. auto length = std::vsnprintf(buffer, sizeof(buffer), format, args);
  49. va_end(args);
  50. if (length < 0) { // something wrong
  51. message = {};
  52. } else if (length < sizeof(buffer)) {
  53. message = string(buffer, static_cast<unsigned long>(length));
  54. } else {
  55. message.resize(static_cast<unsigned long>(length), '\0');
  56. va_start(args, format);
  57. std::vsnprintf(const_cast<char *>(message.data()), static_cast<size_t>(length) + 1, format, args);
  58. va_end(args);
  59. }
  60. if (g_logHandler) {
  61. g_logHandler(level, filename, line, func, message);
  62. } else {
  63. auto desc = MMKVLogLevelDesc(level);
  64. __android_log_print(desc, APP_NAME, "<%s:%d::%s> %s", filename, line, func, message.c_str());
  65. }
  66. }
  67. }
  68. # endif // MMKV_ANDROID
  69. #endif // ENABLE_MMKV_LOG